java中的简单线程问题

JPC*_*JPC 0 java concurrency multithreading synchronization

除了我释放爬虫时的工作:

public void setCrawlerFree(WebCrawler w)
    {
        synchronized(myFreeCrawlers)
        {
            synchronized(numToGo)
            {
                myFreeCrawlers.add(w);
                myFreeCrawlers.notifyAll();
                numToGo--;
                numToGo.notify();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

爬虫完成后,我可以将其添加回列表中.我还想从我仍然需要做的事情中减去1.我有一个主线程等待,直到numToGo为0.我在numToGo.notify()上得到一个IllegalMonitorStateException,但由于它在同步块内,这是不是意味着我拥有它?

Eug*_*hov 7

考虑将其重写为ExecutorService.

ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, 
     maximumPoolSize, keepAliveTime, timeUnit, 
     new LinkedBlockingQueue<Runnable>());
executor.submit(new Callable<...>() { ... });
Run Code Online (Sandbox Code Playgroud)

它将大大简化您的代码并消除线程同步问题.