我创建了一个带有 的线程池Executors.newFixedThreadPool
,但过了一段时间我注意到其中一些停止了回答(在下面调用此方法)。
他们被摧毁了?我进行同步,当所有线程设置完成任务时系统继续,但是这样,系统进入死锁。
他们被摧毁了?我能做些什么来防止或处理这种情况?
//this is the method that threads call when finish the work
synchronized void setTaskFinish(){
System.out.println(Thread.currentThread().getName() + " finishing the work.");
finishedThreads++;
System.out.println(finishedThreads +" finished the work.");
if(finishedThreads == numberThreads){
finishedThreads = 0;
this.notify();
}
}
//this is the method that creates the thread
//I dont know much about this executors yet, so I think it have errors
public void execute(int numberThreads) {
for (int i = 0; i < numberThreads; i++) {
crawlers.add(new SlaveCrawler());
}
ExecutorService threadExecutor = Executors.newFixedThreadPool(numberThreads);
for (int i = 0, n = crawlers.size(); i < n; i++) {
threadExecutor.execute((Runnable) crawlers.get(i));
}
threadExecutor.shutdown();
}
编辑:我完全改变了我的逻辑。我没有做太多的测试,但现在一切似乎都很好。也许我的旧逻辑有问题。