简体   繁体   中英

Stop all threads in a custom thread pool (like shutting down)

In Java library thread pool implementations, usually shutting down a pool means:

-stop accepting new tasks

-previously submitted tasks are executed

-all pool threads are terminated

Regarding the last point, how would you stop a pool thread that could potentially try to take a new task, after it has been stopped?

My threads do something like this (in java pseudo code):

public void run() {
  while(!isStopped) {
    Task task = taskQueue.take(); //line1
    task.run(); //line2
  }
}

and have a method stop:

public synchronized void stop(){
  isStopped = true;
  this.interrupt();
}

In my thread pool class, I have a method stop:

public synchronized void shutdown(){
  this.isShutdown = true; //to stop the whole pool
  for(PoolThread thread : threads)
    thread.stop();
}

The point is, if a thread reaches line 1, isStopped was false, but at that same moment it could be set to true by the pool class. How do I remember that I should stop the thread again? Does calling interrupt suffice?

Send the shutdown messages through the task queue:

static Task stop = // some special value

public void run() {
  while (true) {
    Task task = taskQueue.take();
    if (task == stop) {
        break;
    }
    task.run();
  }
}

and in shutDown :

public synchronized void shutdown(){
  if (isShutdown) {
    return;
  }
  this.isShutdown = true;
  for(PoolThread thread : threads) {
    taskQueue.put(PoolThread.stop);
  }
}

With a number of shutdown messages in the queue equal to the number of threads, once all work is completed, the threads will each take a shutdown message and shut down. (Note that we don't need to care about which thread gets which shutdown message.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM