Java Core Knowledge Point---thread pool threadpool

Source: Internet
Author: User

Thread pool is a key point to be mastered in multi-threaded learning.

The cost of starting a new thread is higher because it involves interacting with the operating system. In this scenario, using the thread pool can improve performance, especially if you need to consider using a thread pool when you want to create a lot of short-lived threads in your program.

I. How do I create a thread pool??

Before Java5, the thread pool was developed manually, and from Java5 onwards, Java was built to support the thread pool. The main is to add a executors factory class to the production line pool .

1.newCachedThreadPool (): Creates a thread pool with caching capabilities, and the system creates threads as needed, which are cached into the thread pool.

2.newfixedthreadpool(int nthreads): Creates a reusable thread pool with a fixed number of threads.

3.newSingleThreadExecutor (): Creates a thread pool with only one thread, which is equivalent to calling the Newfixedthreadpool () method to pass in a parameter of 1;

4.newScheduledThreadPool (int corepoolsize) refers to the number of threads held in the pool, even if the thread is idle and is saved online Cheng;

5.newSingleThreadScheduledExecutor (): Creates a thread pool with only one threads, which can perform thread tasks after a specified delay;

The first 3 methods in the above 5 methods return a Executorservice object that represents a thread pool that can execute the threads represented by the Runnable object or callable object; The next 2 methods return a Scheduledexecutorservice thread pool, which is a subclass of Executorservice.

two. How do I use the thread pool?

Example:

Package Com.amos.concurrent;import Java.util.list;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.timeunit;/** * @ClassName: Threadpooltest * @Description:     Thread pool in Java5 * @author: amosli* @email: [email protected]* @date Apr, 2:13:27 AM */public class Threadpooltest { public static void Main (string[] args) {//Executorservice Executorservice = Executors.newfixedthreadpool (3);// Set the number of threads fixed//Executorservice Executorservice = Executors.newcachedthreadpool ();//Create a thread pool with a cache, automatically assign the number of threads Executorser vice Executorservice = Executors.newsinglethreadexecutor ();//create a single thread pool, how to implement a thread is dead, and automatically re-build a Executors.newscheduledthre Adpool (3). Schedule (new Runnable () {//Creates a thread pool with 3 threads and executes the contents of the Run method after 3 seconds of the public void Run () {System.            Out.println ("Bomb ...");  }}, 3, timeunit.seconds);//3 seconds for (int i = 0; i < x i++) {//Create 10 task final int    task = i;        Executorservice.execute (New Runnable () {//thread public void run () executing task () {for (int i = 0; I < 10; i++) {//loop executes 10 times System.out.println (Thread.CurrentThread (). GetName () + "loop" + i + "task is" +                    Task);        }                }            });        } System.out.println ("All of the ten task has committed!!"); list<runnable> Shutdownnow = Executorservice.shutdownnow ();//closes the thread immediately and returns the thread System.out.println not executed ("closed thre        Ad Size: "+shutdownnow.size ());        for (Runnable A:shutdownnow) {System.out.println (a); }    }}

Operating effect:

Create a single thread pool , add tasks to the thread pool, have 9 threads closed, and execute output ' bomb ... after 3 seconds. '

three. Thread Pool usage Considerations

1. Executors.newfixedthreadpool () is more commonly used in daily development.

2. How do I perform tasks on a regular basis?

When performing a task at a specified time, for example to run at 12:00 noon, you can schedule (task, date.gettime ()-
System.currenttimemillis (), timeunit.milliseconds). It also uses a countdown to perform timed operations, which is recommended by the official Java documentation.

3. Expansion --- run a task every 2 seconds for one hours

Package Com.amos.concurrent;import static Java.util.concurrent.timeunit.seconds;import Java.util.date;import Java.util.concurrent.executors;import Java.util.concurrent.scheduledexecutorservice;import Java.util.concurrent.scheduledfuture;class Beepercontrol {Private finalScheduledexecutorservice Scheduler = Executors.newscheduledthreadpool (1); public void Beepforanhour () {final Runnable beeper = new Runnable () {public void run () {Sy            Stem.out.println (New Date (). getseconds ());//Timing System.out.println ("beep"); }        };final Scheduledfuture beeperhandle = Scheduler.scheduleatfixedrate (beeper, 2, SECONDS);//task, 10s delay,2s/times, Unit sec scheduler.schedule (new Runnable () {public void run () {b Eeperhandle.cancel (TRUE);//Undo Task}, *, SECONDS);//60*60s=60min=1h}}public class test{Publ IC static void Main (string[] args) {System.out.println (New Date (). getseconds ());//Timing New Beepercontrol (). be    Epforanhour (); }}


This example, is provided by the Java official, here slightly modified, the effect of the following:

Note: The first run is in 0 seconds, 10 seconds after the first beep, and then every 2 seconds beep once;

The first is to create a task thread pool: Executors.newscheduledthreadpool (1), set the number of threads to 1, then implement a runnable interface, and then call the Scheduleatfixedrate method, Specify the frequency, specify the delay, perform the beep task, and finally implement a runnable interface that delays 1 hours to perform the task of undoing the thread.

Java Core Knowledge Point---thread pool threadpool

Related Article

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.