Java ThreadPool usage

前端 未结 6 1834
感动是毒
感动是毒 2020-12-30 14:17

I\'m trying to write a multithreaded web crawler.

My main entry class has the following code:

ExecutorService exec = Executors.newFixedThreadPool(num         


        
6条回答
  •  渐次进展
    2020-12-30 14:49

    I think use of wait/notify is justified in this case. Can't think of any straight forward way to do this using j.u.c.
    In a class, let's call Coordinator:

    private final int numOfCrawlers;
    private int waiting;
    
    public boolean shouldTryAgain(){
        synchronized(this){
            waiting++;
            if(waiting>=numOfCrawlers){
                //Everybody is waiting, terminate
                return false;
            }else{
                wait();//spurious wake up is okay
                //waked up for whatever reason. Try again
                waiting--;
                return true;
            }
        }
    
    public void hasEnqueued(){
        synchronized(this){
            notifyAll();
        }
    } 
    

    then,

    ExecutorService exec = Executors.newFixedThreadPool(numberOfCrawlers);
    while(true){
        URL url = frontier.get();
        if(url == null){
            if(!coordinator.shouldTryAgain()){
                //all threads are waiting. No possibility of new jobs.
                return;
            }else{
                //Possible that there are other jobs. Try again
                continue;
            }
        }
        exec.execute(new URLCrawler(this, url));
    }//while(true)
    

提交回复
热议问题