Multithreaded Simple instance (3) thread pool

Source: Internet
Author: User

Why use a thread pool?

Every time you use a thread, go to new one, no trouble. If the thread is less than possible. Threads are frequently created when a large number of threads are needed, and the overhead associated with creating threads and destroying them increases.

The thread pool is like an executor. And the business logic that we need to execute is inside the Run method that we wrote to implement the Runnable interface.

To throw it into the thread pool, I just need to make sure my business logic is implemented in run. Execute a thread-finding pool for this foundry.

Thread pool Threadpoolexecutor class, the following is how the class is constructed.

 Public classThreadpoolexecutorextendsAbstractexecutorservice {... PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>workQueue);  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>workqueue,threadfactory threadfactory);  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>Workqueue,rejectedexecutionhandler handler);  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>workqueue,threadfactory Threadfactory,rejectedexecutionhandler handler); ...}

Main parameter Description:

Corepoolsize: Number of core threads
Maximumpoolsize: Maximum number of threads (can be imagined as hyper-overclocking in the CPU)
KeepAliveTime: Thread No task survival time (typically, the current number of threads poolsize greater than corepoolsize, will destroy the idle time is greater than the keepalivetime of the thread, until the current number of threads is not greater than corepoolsize)
Units of Unit:keepalivetime (
Timeunit.days;               Days Timeunit.hours;             Hour timeunit.minutes;           Minutes Timeunit.seconds;           Seconds timeunit.milliseconds;      Ms Timeunit.microseconds;      Subtle timeunit.nanoseconds;       Na-Sec


Blockingqueue<runnable>: The maximum number of task threads allowed in the cache queue (added to the cache queue when the number of threads is greater than maxnumpoolsize)
Some methods of Threapoolexecutor:
Execute (): Thread pool joins threads
Submit (): The thread pool joins threads (as with the Execute method, except that it returns a parameter.) PS: In fact, the inside of the submit is also called the Execute method)
Shutdown (): Closes the thread pool (if there are still threads in the thread pool and cache that are not executed, it will continue to execute, emptying the thread pools.) )
Shutdownnow (): Close the thread pool immediately (throws an exception if there are still threads in the thread pools that are not executed)

A simple example:
 PackageCode.thread;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit;//thread Pool Public classThreadPool { Public Static voidMain (string[] args) {threadpoolexecutor ThreadPool=NewThreadpoolexecutor (5, 10, 200, Timeunit.microseconds,NewArrayblockingqueue<runnable> (5));  for(inti=0;i<15;i++) {Threadpool.execute (NewTask (i)); System.out.println (Threads in thread pool: number of threads waiting in +threadpool.getpoolsize () + queue: "+threadpool.getqueue (). Size ()+ "Number of threads executed:" +Threadpool.getcompletedtaskcount ()); }        {            Try{Thread.Sleep (5000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println (Threads in thread pool: number of threads waiting in +threadpool.getpoolsize () + queue: "+threadpool.getqueue (). Size ()+ "Number of threads executed:" +Threadpool.getcompletedtaskcount ());                    } threadpool.shutdown (); }}classTaskImplementsRunnable {Private inti;  PublicTask (inti) { This. i =i; } @Override Public voidrun () {System.out.println ("Task:" +i+ "execute"); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Task:" +i+ "Execution End"); }    }

Execution Result:

Number of threads in the

task:0 execution
Thread pool: 1 Threads waiting in queue: 0 threads executed: 0
Threads in thread pool: 2 Number of threads waiting in queue: 0 Number of threads executed: 0
task:1 execution
Threads in thread pool: 3 Number of threads waiting in queue: 0 threads executed: 0 threads in
Task:2 execution
Thread pool: 4 Number of threads waiting in queue: 0 threads executed: 0
Task:3 Execution
Thread pool: 5 Number of threads waiting in the queue: 0 Number of threads executed: 0 Number of threads in the
Task:4 execution
Thread pool: 5 threads waiting in queue: 1 threads that have been executed: 0
Threads in thread pool: 5 threads waiting in queue: 2 number of threads that have run: 0
Thread pool: 5 Number of threads waiting in queue: 3 threads executed: 0 threads in thread pool: 5 Number of threads waiting in queue: 4 threads executed: 0
Threads in thread pool: 5 Number of threads waiting in the queue: 5 number of threads that have been executed: 0
Threads in thread pool: 6 Number of threads waiting in queue: 5 threads executed: 0 threads in
task:10 execution
Thread pool: 7 Number of threads waiting in queue: 5 threads executed: 0
task:11 execution
task:12 execution
Thread pool threads: 8 Number of threads waiting in queue: 5 threads executed: 0
Threads in thread pool: 9 Threads waiting in queue: 5 threads executed: 0
task:13 executing
task:14 execution
Thread pool: 10 Number of threads waiting in queue: 5 Number of threads executed: 0
task:0 execution end
Task:2 execution end
Task:5 execution
task:1 execution End
Task:6 execute
Task:3 execution end
Task:8 Execute
Task : 4 execution End
Task:9 execution
task:13 execution end
Task:7 execution
task:10 execution end
Task:11 execution end
Task:12 execution end
task:14 execution End
Task:5 execution End
Task:6 execution end
Task:7 execution end
Task:9 execution end
Task:8 execution End
Thread pool number of threads: 5 Number of threads waiting in the queue: 0 Number of threads executed:

Multithreaded Simple instance (3) 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.