简体   繁体   中英

Java Thread Pool Purpose

I am trying to understand the concept of thread pools in Java. In order to do this, I am reading various tutorials including this one .

As the tutorial states:

There is a performance overhead associated with starting a new thread,
and each thread is also allocated some memory for its stack etc.

However, the code listed in there means that the thread is going to die after the end of the execution of the runnable dequed from the task queue and thus, its resource will be utilized and garbage collected by JVM:

public void run(){
    while(!isStopped()){
      try{
        Runnable runnable = (Runnable) taskQueue.dequeue();
        runnable.run();
      } catch(Exception e){
        //log or otherwise report exception,
        //but keep pool thread alive.
      }
    }
  }

So if the thread dies what is the purpose of the whole thing then? I thought that the thread in a thread pool should be analogous to a looper and should sleep and wake up when the runnable is passed, and when it's done with the runnable would go back to sleep without being destoroyed , so the resource can potentially be reused - not garbage collected .

So am I understanding the whole concept in a wrong way? Or is it just a simplified example that I over evaluated?

The thread in your code sample is not going to die after the end of the execution of the runnable.

There is a while loop there, so it will loop and start processing the next element.

public void run(){

    //If isStopped() equals false you can run the taskQueue. This means you have  
    //not stopped your thread.
    //!isStopped() is the same as isStopped = false
    //You need to invoke stop() method to stop your thread

    while(!isStopped()){
      try{
        Runnable runnable = (Runnable) taskQueue.dequeue();
        runnable.run();
      } catch(Exception e){
        //log or otherwise report exception,
        //but keep pool thread alive.
      }
    }
  }

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