我创建了一个使用线程从文件中读取数据并进行支付的程序。正在获取Null指针异常,第一次线程1从文本文件中打印firstrecord,而从文件中删除的第二个数据则抛出null指针
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService es = Executors.newSingleThreadExecutor();
List<String> tasks = getUsersFromFile("new_users.txt");
DoctorDao dao = new DoctorDao();
for (String data : tasks) {
Future<Boolean> result = es.submit(new DoctorTask(data, dao));
while (result.get()) {
System.out.println("data stored!!!");
}
}
es.shutdown();
System.out.println("task done!!!");
}
public static List<String> getUsersFromFile(String fileName) {
List<String> users = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
String line = null;
while ((line = reader.readLine()) != null) {
users.add(line);
}
} catch (FileNotFoundException ex) {
// Logger.getLogger(TestExecutors.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
// Logger.getLogger(TestExecutors.class.getName()).log(Level.SEVERE, null, ex);
}
return users;
在Callable实现类中
public Boolean call() throws Exception {
Boolean status = false;
System.out.println(Thread.currentThread().getName() + " processing record for : " + doctorRecord);
StringTokenizer tokenizer = new StringTokenizer(this.doctorRecord, ",");
Doctor doc = null;
while (tokenizer.hasMoreTokens()) {
doc = new Doctor();
doc.setEmailAddress(tokenizer.nextToken());
doc.setName(tokenizer.nextToken());
doc.setId(Integer.valueOf(tokenizer.nextToken()));
status = dao.saveUser(doc);
}
return status;
}
Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at com.executor.demo.readfile.TestDotorExecutor.main(TestDotorExecutor.java:23)
Caused by: java.lang.NullPointerException
at com.executor.demo.readfile.DoctorDao.saveUser(DoctorDao.java:5)
at com.executor.demo.readfile.DoctorTask.call(DoctorTask.java:28)
at com.executor.demo.readfile.DoctorTask.call(DoctorTask.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
答案 0 :(得分:0)
host