Java 线程被破坏了?

Java 线程被破坏了?,java,multithreading,deadlock,destroy,Java,Multithreading,Deadlock,Destroy,我创建了一个带有Executors.newFixedThreadPool的线程池,但过了一段时间,我注意到其中一些线程停止响应(调用下面的方法) 他们被摧毁了?我正在进行同步,当所有线程完成任务时,系统将继续,但这样,系统将进入死锁状态 他们被摧毁了?我能做些什么来防止或处理这种情况 //this is the method that threads call when finish the work synchronized void setTaskFinish(){ System.o

我创建了一个带有
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();        
}
//这是线程在完成工作时调用的方法
已同步的void setTaskFinish(){
System.out.println(Thread.currentThread().getName()+“完成工作”);
finishedThreads++;
System.out.println(finishedThreads+“完成了工作”);
如果(finishedThreads==numberThreads){
finishedThreads=0;
this.notify();
}
}
//这是创建线程的方法
//我对这个遗嘱执行人还不太了解,所以我认为它有错误
public void execute(int numberThreads){
对于(int i=0;i

编辑:我完全改变了我的逻辑。我没有做太多的测试,但现在一切似乎都好了。可能是我的旧逻辑出了问题。

执行器不会破坏正在忙于执行任务的线程。如果您分配了60个任务,并且只有55个“完成”(更准确地说,您的
setTaskFinish()
方法只被调用了55次),则可能会出现异常,过早终止任务。僵局是另一种可能性,但不是我要研究的第一种


当任务抛出未经检查的异常(如
RuntimeException
)时会发生什么情况?它是否从
finally
块调用
setTaskFinish()
?为什么要使用
synchronized
而不是
AtomicInteger
来管理并发性?

听起来您的代码中可能存在死锁或其他问题。一个简短但完整的程序来演示这个问题真的会有帮助…不清楚你所说的“停下来回答”是什么意思。要么线程池中的所有线程都很忙,无法执行更多工作,要么代码在程序中造成死锁。线程池可以在自己空闲时启动和停止线程,但这并不需要您担心。您应该发布一些代码。例如:我正在处理60个线程。执行正常,但在某一点上,只有55个线程设置任务已完成。程序中的活动已停止。我想他们被摧毁了,但我不知道是否发生了这种情况。如果发生,这是我的代码中的错误,否则我将提供另一种类型的解决方案。
setTaskFinish()
出现在哪个类中?为什么要调用
notify()
?setTaskFinish()在MasterCrawler中。我有一个MasterCrawler,可以访问链接并分发给SlaveCrawlers。当一个从机完成时,他们设置他们的任务完成。当所有操作完成后,通知MasterCrawler获取新链接。答案为+1,但我会使用CountDownLatch控制计数和“释放”是的,不清楚他是否真的在发信号通知另一个线程(通过
notify()
)继续,或者只是在计数线程。如果是前者,闩锁将最容易使用。我从未听说过AtomicInteger。这是什么?我没有在finally块中调用setTaskFinish(),但我没有看到任何异常。无论如何,我改变了所有这些,所以我需要运行新的测试来确定线程是否仍在“消失”。