Java Multithreading Series--Introduction to Thread pool

Source: Internet
Author: User

What is a thread pool?

To prevent the system from creating and destroying threads frequently, we can reuse the created threads.
Gets from the thread pool when the thread is used, does not destroy the thread after it is exhausted, and is returned to the thread pool.

JDK support for the thread pool

To better control multi-threading, the JDK provides a thread pool framework, as shown in

They are all in the Java.util.concurrent package.

    • Executor is used to perform the task, which provides the execute () method to perform the Runnable task;
    • Threadpoolexecutor represents a thread pool;
    • Executors it is a static factory factory class, through which it can obtain a thread pool with specific functions;
Thread pools with different characteristics
    1. Newfixedthreadpool (): Returns a fixed number of thread pools. The number in the thread pool is always the same. When a new task is committed, the thread pool is executed immediately if it has an idle thread. If none is placed in the task queue, the tasks in the task queue are processed when there are idle threads waiting.
    2. Newsinglethreadpool (): Returns the thread pool of only one thread. If more than one task is committed, it is placed in the task queue and waits for idle threads to execute the tasks in the queue in first in, first out order.
    3. Newcachedthreadpool (): Returns a thread pool that can adjust the number of threads according to the actual situation. The thread pool created by this method can be expanded wirelessly and will shrink automatically when demand is reduced.
    4. newsinglethreadscheduledexecutor (): Returns a Scheduledexecutorservice object with a thread pool size of 1. The Scheduledexecutorservice interface extends the ability to perform a task at a given time on top of the Executorservice interface, after a fixed time delay, or periodically executing a task.
    5. Newscheduledthreadpool (): Returns a Scheduledexecutorservice object and can specify the number of threads.
    6. Scheduledexecutorservice does not necessarily immediately arrange for the execution of tasks, but rather plays a role in planning tasks.
    7. It has three main methods:
      1. Schedule (): Schedules a task at a given time
      2. Scheduleatfixedrate (): Creates and executes a recurring action that is first enabled after a given initial delay, with a given period for subsequent operations
      3. Schedulewithfixeddelay (): Creates and executes a recurring action that is first enabled after a given initial delay, followed by a given delay between each execution termination and the next execution start
Example
ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Created by zhengbin on 2017/10/24*/ Public classExecutorservicetest {Private Static classTaskImplementsRunnable { Public voidrun () {System.out.println (System.currenttimemillis ()+ ": Thread ID:" +Thread.CurrentThread (). GetId ()); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {Task T=NewTask (); Executorservice Executorservice= Executors.newfixedthreadpool (5);  for(inti = 0; I < 10;i++) {Executorservice.execute (t);    } executorservice.shutdown (); }}
Run results
1509258535474:thread Id:111509258535474:thread Id:121509258535475:thread Id:141509258535475:thread Id:151509258535475:thread Id:131509258536475:thread Id:151509258536475:thread Id:111509258536475:thread Id:121509258536475:thread Id:141509258536475:thread id:13
Result description

The main thread creates a fixed-size thread pool with a thread pool capacity of 5.

The running result outputs the running timestamp, and you can see that the time stamp for the first 5 tasks is 1000 milliseconds from the timestamp of the last 5 tasks.

This shows that in these 10 tasks, it is performed in 2 batches. This also fully conforms to the behavior of a thread pool with only 5 threads.

When the thread pool is changed to Newcachedthreadpool (), 10 tasks are executed at the same time.

Java Multithreading Series--Introduction to Thread pool

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.