我是多线程的新手。我试图使用Crud存储库在sql数据库中保存对象列表。但是我在保存操作中得到了空指针异常。 下面是我的代码和异常。 线程类
public class PrescriptionThread implements Runnable{
private MedicineService medServ = new MedicineService();
private Presciption pres ;
public PrescriptionThread(Presciption pres) {
this.pres = pres;
}
@Override
public void run() {
medServ.savePrescription(pres);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
服务等级
@Service
public class MedicineService {
@Autowired
private PrescriptionRepository presRepo;
public void storePrescription(List<Presciption> payload) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (Presciption presciption : payload) {
Runnable runnable = new PrescriptionThread(presciption);
executorService.execute(runnable);
}
executorService.shutdown();
while(!executorService.isTerminated()) {}
}
public synchronized void savePrescription(Presciption pres) {
presRepo.save(pres);
}
}
存储库
@Repository
public interface PrescriptionRepository extends CrudRepository<Presciption, Integer> {
}
我正在接受治疗 presRepo.save(pres);
Exception in thread "pool-1-thread-3" Exception in thread "pool-1-thread-1" Exception in thread "pool-1-thread-2" java.lang.NullPointerException
at com.cerner.api.service.MedicineService.savePrescription(MedicineService.java:86)
at com.cerner.api.util.PrescriptionThread.run(PrescriptionThread.java:16)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
如果我不使用线程而只是说
for (Presciption presciption : payload) {
presRepo.save(pres);
}
它工作正常,我能够将其保存到数据库。但是我想实现线程。 预先感谢。
答案 0 :(得分:0)
作为此处的结果:
private MedicineService medServ = new MedicineService();
实例“ medServ”是春季IOC管理,如果您“新建”它,也许因为它是“ @Autowire”而没有得到“ PrescriptionRepository”的实例,则在您调用{{1 }}。但是如果您不使用Thread,则意味着实例本身不是新的,因此可以正常工作
答案 1 :(得分:0)
我如下修改了我的线程类,并且能够获得bean。
result = np.array([[2,2],[3,3],[4,4]])