【发布时间】:2016-04-13 18:52:27
【问题描述】:
我必须将员工数据从文本文件(每条记录由制表符分隔)读取到 ArrayList 中。然后我必须将这个员工对象从列表中插入到数据库中的员工表中。为此,我将逐个迭代列表元素,并将员工详细信息一次插入数据库。在性能方面不推荐这种方法,因为我们可以有超过 10 万条记录,并且插入整个数据需要很长时间。
我们如何在将数据从列表插入到数据库时使用多线程来提高性能。另外我们如何使用 CountDownLatch 和 ExecutorService 类来优化这个场景。
读写测试
public class ReadWriteTest {
public static void main(String... args) {
BufferedReader br = null;
String filePath = "C:\\Documents\\EmployeeData.txt";
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filePath));
List<Employee> empList = new ArrayList<Employee>();
while ((sCurrentLine = br.readLine()) != null) {
String[] record = sCurrentLine.split("\t");
Employee emp = new Employee();
emp.setId(record[0].trim());
emp.setName(record[1].trim());
emp.setAge(record[2].trim());
empList.add(emp);
}
System.out.println(empList);
writeData(empList);
} catch (IOException | SQLException e) {
e.printStackTrace();
}
}
public static void writeData(List<Employee> empList) throws SQLException {
Connection con =null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
for(Employee emp : empList)
{
PreparedStatement stmt=con.prepareStatement("insert into Employee values(?,?,?)");
stmt.setString(1,emp.getId());
stmt.setString(2,emp.getName());
stmt.setString(3,emp.getAge());
stmt.executeUpdate();
}
}catch(Exception e){
System.out.println(e);
}
finally{
con.close();
}
}
}
员工类
public class Employee {
String id;
String name;
String age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
EmployeeData.txt
1 Sachin 20
2 Sunil 30
3 Saurav 25
【问题讨论】:
标签: java multithreading