[Java] ThreadPool Usage and examples

Source: Internet
Author: User

1, the advantages of ThreadPool

Under the Java.util.concurrent package, a series of classes related to the thread pool are provided. A reasonable use of the thread pool can bring several benefits:
  
(1) Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created;
(2) Improve the response speed. When the task arrives, the task can be executed without waiting for the thread to be created;
(3) Improve the manageability of threads. Threads are scarce resources that, if created indefinitely, not only consume system resources, but also reduce system stability, using a thread pool for uniform allocation, tuning, and monitoring.

The thread pool can respond to sudden bursts of traffic, with a limited number of fixed threads serving a large amount of operations, reducing the time required to create and destroy threads.

1, the creation of ThreadPool

We typically create the corresponding thread pool through the four member functions under the Executors class:

//创建一个定时任务的线程池ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);//创建单线程的线程池ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();//创建缓存线程池(重用先前的线程)ExecutorService cachedThreadPool = Executors.newCachedThreadPool();//创建一个带有固定线程的线程池ExecutorService threadPool = Executors.newFixedThreadPool(4);

As we can see from the source, the above four methods call Threadpoolexecutor's construction method to create the thread pool.

publicstaticnewFixedThreadPool(int nThreads) {        returnnew ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());    }

Creating a Threadpoolexecutor thread pool typically requires the following parameters:

  • Corepoolsize (basic size of the thread pool):

    When a task is submitted to the thread pool, the line pool creates a thread to perform the task, and the thread is created even if other idle basic threads are able to perform new tasks, and is no longer created until the number of tasks that need to be performed is greater than the thread pool base size. If the thread pool's Prestartallcorethreads method is called, the thread pool creates and starts all basic threads in advance.

  • Maximumpoolsize (maximum thread pool size):

    The maximum number of threads allowed to be created by the thread pool. If the queue is full and the number of threads that have been created is less than the maximum number of threads, the thread pool will then create new threads to perform the task. It is worth noting that if you use the unbounded task queue This parameter has little effect.

  • KeepAliveTime (thread activity hold time):
      
    When the worker thread of the thread pool is idle, the time to remain alive. So if the task is a lot, and each task executes a short time, you can adjust the time to increase the utilization of the thread.

  • Timeunit (unit of thread activity hold time):

    The optional units are day (days), hours (HOURS), minutes (MINUTES), milliseconds (MILLISECONDS), etc.
      

  • WorkQueue (Task queue):

    The blocking queue that is used to hold tasks waiting to be executed. You can select the following blocking queues: Arrayblockingqueue, Linkedblockingqueue, Synchronousqueue, Priorityblockingqueue
      

  • Threadfactory:
      
    Used to set the factory for creating threads, you can set a more meaningful name for each thread created by the thread factory.
      
  • Handler (saturation strategy):
      
    When the queue and thread pool are full, indicating that the thread pools are saturated, a policy must be taken to handle the new tasks that are submitted. This policy is abortpolicy by default, indicating that an exception is thrown when a new task cannot be processed.

    We try to use the static method provided by executors to create the thread pool, and if the method provided by executors does not meet the requirements, then you can create it yourself through the Threadpoolexecutor class.

2. Submit a task to the thread pool

There are two ways of doing this:

① we can use the task submitted by execute, but the Execute method does not return a value, so it is not possible to determine whether the task was successfully executed by the thread pool. The following code shows that the task entered by the Execute method is an instance of the Runnable class.

threadsPool.execute(new Runnable() {            @Override            publicvoidrun() {                // TODO Auto-generated method stub            }        });

② using the Submit method to submit the task, it will return a future, then we can use this future to determine whether the task is successful, through the future get method to get the return value, the Get method will block until the task is completed, and use Get (long Timeout, Timeunit unit) method will be blocked for a period of time immediately after the return, it is possible that the task is not finished.

Future<Object> future = executor.submit(harReturnValuetask);try {     Objectcatch (InterruptedException e) {    // 处理中断异常catch (ExecutionException e) {    // 处理无法执行任务异常finally {    // 关闭线程池    executor.shutdown();}
3. Thread pool shutdown

We can turn the thread pool off by invoking the shutdown or Shutdownnow methods of the thread pools (Executorservice objects), by traversing the worker threads in the thread pooling, and then calling the thread's interrupt method one by one, Therefore, a task that cannot respond to an outage may never be terminated. But there are some differences, Shutdownnow first sets the state of the thread pool to stop, then tries to stop all the threads that are executing or pausing the task, and returns a list of waiting tasks, while shutdown only sets the state of the thread pool to shutdown state. It then interrupts all threads that are not performing the task.

The IsShutDown method returns true whenever one of the two closing methods is called. The call to the Isterminaed method returns True when all tasks have been closed to indicate that the thread pool was successfully closed. As to which method we should call to close the thread pool, it should be determined by the task attributes submitted to the thread pool, usually called shutdown to close the thread pool, and shutdownnow can be called if the task is not necessarily finished.

4. Workflow of thread pool

   

As we can see, when a new task is submitted to the thread pool, the thread pool processes the following:

1, first the thread pool to determine whether the basic thread pool is full (corepoolsize) is not full, create a worker thread to perform the task. Full, then go to the next process.

2, the next thread pool to determine whether the work queue is full? is not full, the newly submitted task is stored in the work queue. Full, then go to the next process.

3. The last thread pool determines if the entire thread pool is full (< maximumpoolsize? )? is not full, a new worker thread is created to perform the task, and the saturation policy is assigned to handle the task.

That is, the thread pool takes precedence over the number of threads that create a basic thread pool size (corepoolsize), and when this number is not reached, each time a new task is committed, a new thread is created, and when the number of basic threads is reached, a new task arrives, priority is placed in the waiting queue, and if the queue is full, To create a new thread (cannot exceed the maximum number of thread pool maxmumpoolsize).

When the thread pool creates threads, the thread is encapsulated as a worker thread worker,worker the tasks in the work queue are executed indefinitely after the task is completed. We can see this from the worker's Run method:

publicvoidrun() {     try {           Runnable task = firstTask;           null;            whilenullnull) {                    runTask(task);                    null;            }      finally {             workerDone(this);      
5, the thread pool monitoring

By inheriting the thread pool and overriding the Beforeexecute,afterexecute and terminated methods of the thread pool, we can do something before the task executes and before the thread pool shuts down. such as the average execution time of the monitoring task, the maximum execution time and the minimum execution time. These several methods of online constructor are empty methods.

6. Example of thread pool

Example one:

 Public  class differentkindsthreadpool {     Public Static void Main(string[] args) {//Displayscheduledthreadpool ();//Displaysinglethreadpool ();//Displaycachedthreadpool ();Displaythreadpool (); }/** * Create a thread pool for timed tasks * /     Public Static void Displayscheduledthreadpool() {Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (4);//It can perform tasks like a fixed thread poolDistributetaskforthreadpool (Scheduledthreadpool);//This is its special place and can be scheduled tasksScheduledthreadpool.schedule (NewRunnable () {@Override                     Public void Run() {System.out.println ("Start performing task 1"); }                },5, timeunit.seconds);//re-perform the task again every 2 secondsScheduledthreadpool.scheduleatfixedrate (NewRunnable () {@Override                     Public void Run() {System.out.println ("Start performing task 2"); }                },5,3, timeunit.seconds); }/** * Create a thread pool with only one threads, if the thread terminates, * He will create a new thread to join the pool, which will ensure that there is always a thread in the pool */     Public Static void Displaysinglethreadpool() {Executorservice singlethreadpool = Executors.newsinglethreadexecutor ();    Distributetaskforthreadpool (Singlethreadpool); }/** * Creates a thread pool that can create threads as needed, but * when the previously created thread is available, it reuses the previous line *, and if there are no available threads, a new thread * will be created and added to the pool. Threads that have not been used for 60 seconds will be terminated and removed from the cache * /     Public Static void Displaycachedthreadpool() {Executorservice cachedthreadpool = Executors.newcachedthreadpool ();    Distributetaskforthreadpool (Cachedthreadpool); }/** * Create a thread pool with fixed threads * /     Public Static void Displaythreadpool() {//Create a thread pool with 4 fixed threadsExecutorservice ThreadPool = Executors.newfixedthreadpool (4);    Distributetaskforthreadpool (ThreadPool); }/** * Assign 8 tasks to the thread pool so that it drives * @param threadPool */     Public Static void Distributetaskforthreadpool(Executorservice ThreadPool) {//Let the thread pool drive 8 Tasks         for(inti =1; I <=8; i++) {//Because the inner class cannot put a non-final variable, I assign the value of I to the task            Final inttask = i; Threadpool.execute (NewRunnable () {@Override                 Public void Run() {System.out.println ("I Am"+ Thread.CurrentThread (). GetName () +","+"Got the first."+ Task +"A task, I began to execute.");        }            }); }    }}

Example two:

publicclass BankCount {    publicvoidaddMoney(int money){//存钱        System.out">存入:" + money);    }    publicvoidgetMoney(int money){//取钱        System.out">取钱:" + money);    }}
 Public classbanktest { Public Static void Main(string[] args) {Final Bankcount Bankcount =NewBankcount (); Executorservice executor = Executors.newfixedthreadpool (Ten); Executor.execute (NewRunnable () {//Savings thread@Override Public void Run() {inti =5; while(i-->0) {Bankcount.addmoney ( $);Try{Thread.Sleep ( -); }Catch(Interruptedexception e)                    {E.printstacktrace ();        }                }            }        }); future<?> future = Executor.submit (NewRunnable () {//Take money thread@Override Public void Run() {inti =5; while(i-->0){Try{Thread.Sleep ( -); }Catch(Interruptedexception e)                    {E.printstacktrace (); } Bankcount.getmoney ( $); }            }        });Try{Object res = future.Get(); System. out. println (RES); }Catch(Interruptedexception e) {//Handle Interrupt ExceptionE.printstacktrace (); }Catch(Executionexception e) {//Handle Unable to perform task exceptionE.printstacktrace (); }finally{//close thread poolExecutor.shutdown (); }    }}

Reference article:

"Java Advanced" ThreadPool usage and benefits

[Java] threadpool usages and examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.