Java creates a thread pool in 4 ways

Source: Internet
Author: User
Tags object object

Java Thread Pool usage instructions

The role of the thread pool:
The thread pool function is to limit the number of threads executing in the system.
According to the environment of the system, the number of threads can be set automatically or manually to achieve the best performance; less waste of system resources, more caused by the system congestion efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue is executed. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.

Common thread Pools in Java

    1. Newsinglethreadexecutor
      Creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.
      2.newFixedThreadPool
      Creates a fixed-size thread pool. Each time a task is committed, a thread is taken from the thread pool until the thread reaches its maximum size. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.
      1. Newcachedthreadpool
        Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task,
        Then a partially idle (60 second non-performing) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.
        4.newScheduledThreadPool
        Create a thread pool that supports timing and periodic execution of tasks. Can be used in most cases to replace the timer class

Single thread thread pool Executors.newsinglethreadexecutor ()

Import Java.util.concurrent.callable;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Chi {public static void main (string[] args) {/* No thread pool notation Run        nable r = new Myrunnable ();        Thread t = new Thread (r);        T.start (); */executorservice e =executors.newsinglethreadexecutor ();//create a single thread pool E.submit (new myrunnable ());        E.submit (New myrunnable ());        E.submit (New myrunnable ());        E.submit (New myrunnable ());        E.submit (New myrunnable ());        E.submit (New myrunnable ());    E.shutdown (); }}class myrunnable implements runnable{@Override public void Run () {System.out.println ("Give Me a thread:" +thread.cur        Rentthread (). GetName ());            try {System.out.println ("thread starts consuming resources" +thread.currentthread (). GetName ());            Thread.Sleep (2000);        SYSTEM.OUT.PRINTLN ("Thread is finished" +thread.currentthread (). GetName ()); } catch (Interruptedexception e) {e.printstacktRace ();    } System.out.println ("Returned to the thread pool" +thread.currentthread (). GetName ()); }    }

Run results
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1

Create a fixed-length thread pool Executors.newfixedthreadpool ()

Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Chi {public static voi        D main (string[] args) {/* There is no thread pool notation Runnable r = new Myrunnable ();        Thread t = new Thread (r);        T.start (); */executorservice e =executors.newfixedthreadpool (2);//Create a thread pool with two threads Runnable r = new Myrunnable ();        E.submit (R);//Gets a thread object in the thread pool, and then calls the Run method E.submit (R) in the Runnable interface;        E.submit (R);    E.submit (R);//Note that when the Run method runs, threads in the thread do not consume, but are returned to the pool E.shutdown (); }}class myrunnable implements runnable{@Override public void Run () {System.out.println ("Give Me a thread:" +thread.cur        Rentthread (). GetName ());            try {System.out.println ("thread starts consuming resources" +thread.currentthread (). GetName ());            Thread.Sleep (2000);        SYSTEM.OUT.PRINTLN ("Thread is finished" +thread.currentthread (). GetName ());        } catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Return to thread pool" +thread.cUrrentthread (). GetName ()); }    }

Run results
Give me a thread: pool-1-thread-1
Give me a thread: pool-1-thread-2
Thread starts consuming resources pool-1-thread-1
Thread starts consuming resources pool-1-thread-2
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Thread is finished using pool-1-thread-2
Give me a thread: pool-1-thread-1
Thread starts consuming resources pool-1-thread-1
Return to the thread pool Pool-1-thread-2
Give me a thread: pool-1-thread-2
Thread starts consuming resources pool-1-thread-2
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-1
Thread is finished using pool-1-thread-2
Return to the thread pool Pool-1-thread-2

To create a cacheable thread pool

Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Chi {public static voi        D main (string[] args) {/* There is no thread pool notation Runnable r = new Myrunnable ();        Thread t = new Thread (r);        T.start (); */Executorservice e =executors.newcachedthreadpool ();        Runnable r = new Myrunnable ();        E.submit (R);//Gets a thread object in the thread pool, and then calls the Run method E.submit (R) in the Runnable interface;        E.submit (R);    E.submit (R);//Note that when the Run method runs, threads in the thread do not consume, but are returned to the pool E.shutdown (); }}class myrunnable implements runnable{@Override public void Run () {System.out.println ("Give Me a thread:" +thread.cur        Rentthread (). GetName ());            try {System.out.println ("thread starts consuming resources" +thread.currentthread (). GetName ());            Thread.Sleep (2000);        SYSTEM.OUT.PRINTLN ("Thread is finished" +thread.currentthread (). GetName ());        } catch (Interruptedexception e) {e.printstacktrace (); } System.out.println ("Return to thread pool" +thread.currentthRead (). GetName ()); }    }

Run results
Give me a thread: pool-1-thread-1
Give me a thread: pool-1-thread-4
Give me a thread: pool-1-thread-3
Give me a thread: pool-1-thread-2
Thread starts consuming resources pool-1-thread-3
Thread starts consuming resources pool-1-thread-4
Thread starts consuming resources pool-1-thread-1
Thread starts consuming resources pool-1-thread-2
Thread is finished using pool-1-thread-2
Thread is finished using pool-1-thread-3
Thread is finished using pool-1-thread-4
Thread is finished using pool-1-thread-1
Return to the thread pool pool-1-thread-4
Return to the thread pool Pool-1-thread-2
Return to the thread pool pool-1-thread-3
Return to the thread pool pool-1-thread-1

Create a thread pool that can be cached and can perform periodic tasks

Import Java.text.simpledateformat;import Java.util.date;import Java.util.concurrent.executionexception;import Java.util.concurrent.scheduledfuture;import Java.util.concurrent.scheduledthreadpoolexecutor;import Java.util.concurrent.timeunit;public class Chi {public static void main (string[] args) {/* There is no thread pool notation Runn        Able R = new myrunnable ();        Thread t = new Thread (r);        T.start (); */SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Scheduledthreadpoolexecutor e = new Scheduledthreadpoolexecutor (3);//parameter indicates thread capacity SYSTEM.OUT.PRINTLN (SIMPLEDATEFORMAT.F        Ormat (New Date ()));        However, if the task time is approximately 2s, the subsequent tasks will not be executed concurrently. scheduledfuture<?> resultfuture = e.scheduleatfixedrate (New myrunnable (), 0, N, timeunit.milliseconds);// The first parameter task, the second parameter represents the time to wait before the task is executed, the third parameter indicates the task start interval, the fourth parameter represents the time unit e.scheduleatfixedrate (new MyRunnable1 (), 0, a, timeunit.mil  Liseconds);///The first parameter task, the second parameter represents the time to wait before the task is executed, the third parameter indicates the task start interval, and the fourth parameter represents the time unit      Because it is a timed task, the//object Object = Resultfuture.get () is never returned; }}class Myrunnable implements runnable{SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss")    ; @Override public void Run () {System.out.println (Thread.CurrentThread (). GetName () + "Give me a thread:" +simpledateformat.for        Mat (New Date ()));        try {thread.sleep (2000);        } catch (Interruptedexception e) {e.printstacktrace (); }}}class MyRunnable1 implements runnable{SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("Yyyy-mm-dd hh:m    M:ss "); @Override public void Run () {System.out.println (Thread.CurrentThread (). GetName () + "Give me a thread 1:" +simpledateformat.fo        Rmat (New Date ()));        try {thread.sleep (10000);        } catch (Interruptedexception e) {e.printstacktrace (); }    }}

Run results
2018-03-17 13:48:05
Pool-1-thread-1 give me a thread: 2018-03-17 13:48:05
Pool-1-thread-2 give me a thread. 1:2018-03-17 13:48:05
Pool-1-thread-1 give me a thread: 2018-03-17 13:48:07
Pool-1-thread-1 give me a thread: 2018-03-17 13:48:09
Pool-1-thread-3 give me a thread: 2018-03-17 13:48:11
Pool-1-thread-3 give me a thread: 2018-03-17 13:48:13
Pool-1-thread-2 give me a thread. 1:2018-03-17 13:48:15
Pool-1-thread-3 give me a thread: 2018-03-17 13:48:15
Pool-1-thread-3 give me a thread: 2018-03-17 13:48:17
Pool-1-thread-3 give me a thread: 2018-03-17 13:48:19
Pool-1-thread-1 give me a thread: 2018-03-17 13:48:21
Pool-1-thread-1 give me a thread: 2018-03-17 13:48:23
Pool-1-thread-3 give me a thread. 1:2018-03-17 13:48:25
Pool-1-thread-1 give me a thread: 2018-03-17 13:48:25
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

Java creates a thread pool in 4 ways

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.