2

我创建了一个带有 的线程池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();        
}

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

4

1 回答 1

1

执行器不会破坏忙于执行任务的线程。如果您分配了 60 个任务,并且只有 55 个“完成”(更准确地说,您的setTaskFinish()方法只被调用了 55 次),那么提前终止您的任务可能是一个异常。死锁是另一种可能性,但不是我要检查的第一个。

当您的任务抛出未经检查的异常时会发生什么RuntimeException?它是setTaskFinish()从一个finally块调用的吗?为什么您使用synchronized而不是管理并发AtomicInteger

于 2011-05-18T20:05:03.733 回答