我创建了一个程序,使用线程从文件中读取数据并支付。我收到空指针异常,线程 1 第一次从文本文件打印第一条记录,从文件中删除第二个数据,它抛出空指针
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;
在可调用实现的类中
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)
我在代码中犯了一个错误,我从 statiDB 类返回了一个空值,我没有初始化列表对象,所以我修改了代码,
如下所示上面的问题中缺少下面的完整代码
在道课上:
public class DoctorDao {
public boolean saveUser(Doctor doc) {
boolean storedStatus = StaticDB.getDoctorList().add(doc);
return storedStatus;
}
}
在数据库类中
class StaticDB {
static List<Doctor> docList=null;
public static List<Doctor> getDoctorList() {
Doctor doc1 = new Doctor(111,"Shalu","ss@gmail.com");
Doctor doc2 = new Doctor(112,"luke","luke@gmail.com");
docList = new ArrayList<Doctor>(); //This was missing
docList.add(doc1);
docList.add(doc2);
return docList;
}
}