除了我释放爬虫时的工作:
public void setCrawlerFree(WebCrawler w) { synchronized(myFreeCrawlers) { synchronized(numToGo) { myFreeCrawlers.add(w); myFreeCrawlers.notifyAll(); numToGo--; numToGo.notify(); } } }
爬虫完成后,我可以将其添加回列表中.我还想从我仍然需要做的事情中减去1.我有一个主线程等待,直到numToGo为0.我在numToGo.notify()上得到一个IllegalMonitorStateException,但由于它在同步块内,这是不是意味着我拥有它?
考虑将其重写为ExecutorService.
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit, new LinkedBlockingQueue()); executor.submit(new Callable<...>() { ... });
它将大大简化您的代码并消除线程同步问题.