"Java Thread pool Quick Learning Tutorial"

Source: Internet
Author: User

1. Java Thread pool

Thread pool: As the name implies, use a pool to load multiple threads and use a pool to manage multiple threads.

Problem Source: Apply a large number of threads that use the new thread () method to create short execution times, consume more system resources, and slow the system's response. "To what extent can it be judged that the resource consumption of the enabled thread pool is lower than the start ration of the new thread () resource consumption? How does this test? "User experience stalling?" Slow? Watch CPU percent? 】

Workaround: Use thread pooling to manage a large number of threads that have been executed in a short time, by reusing existing threads, reducing the consumption caused by thread creation and destruction, and improving system responsiveness.

2. Java thread Pool Quick Learning Tutorial

2.1 Creating a thread pool

  

Figure 1 Executors static method diagram

2.2 How to use thread pooling

  

Figure 2 Executorservice method diagram

2.3 Thread pool Quick Use example

Problem: The thread pool accepts two threads at the same time, and two threads perform print 1~100 respectively;

1 ImportJava.util.concurrent.ExecutorService;2 Importjava.util.concurrent.Executors;3 4  Public classTest {5      Public Static voidMain (string[] args) {6Executorservice pool =Executors.newcachedthreadpool ();7Pool.submit (NewTestthread ());8Pool.submit (NewTestthread ());9 Pool.shutdown ();Ten     } One  A } -  -  the classTestthreadImplementsrunnable{ - @Override -      Public voidrun () { -          for(inti = 0; I <= 100; ++i) { +System.out.println (Thread.CurrentThread (). GetName () + ":" +i); -             Try { +Thread.Sleep ((Long) (1000L *math.random ())); A}Catch(interruptedexception e) { at e.printstacktrace (); -             } -         } -     } -}
Test.java

3. Thread pool principle:

3.1 Thread pool Threadpoolexecutor

The executors class provides a static factory method, as shown in 1, and these methods are eventually implemented through the Threadpoolexecutor class.

The constructor functions are as follows:

1      PublicThreadpoolexecutor (intCorepoolsize,2                               intMaximumpoolsize,3                               LongKeepAliveTime,4 timeunit Unit,5Blockingqueue<runnable>workQueue) {6          This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,7 executors.defaultthreadfactory (), defaulthandler);8}
Threadpoolexecutor.java

Note:

1, corepoolsize (thread pool base size) >= 0; "Current maximum number of concurrently running threads"

2, maximumpoolsize (maximum thread pool size) >= 1; "Current maximum number of threads created"

3, KeepAliveTime (thread survival hold time) >= 0; "Thread pool idle time exceeds this time and will be terminated"

4. WorkQueue (Task queue) cannot be empty; "Blocking queue for transferring and saving pending tasks"

5. Handler (thread saturation policy) cannot be empty. "Processing policy when the thread pool and queue are full"

3.2 Executors class provides static factory method default parameters

Factory method

Corepoolsize

Maximumpoolsize

KeepAliveTime

WorkQueue

Nrecachedthreadpool ()

0

Integer.max_value

60L

Syschronousqueue

Newfixedthreadpool (int nthreads)

Nthreads

Nthreads

0

Lindedblockingqueue

Newsinglethreadexecutor ()

1

1

0

Lindedblockingqueue

Newscheduledthreadpool (int corepoolsize)

Corepoolsize

Integer.max_value

0

Delayedworkqueue

Newsinglethreadscheduledexecutor ()

1

Integer.max_value

0

Delayedworkqueue

3.3 Thread Pool Add task procedure

Adding a thread is the process of submitting a task that the thread adds to the thread pool:

  

Figure 3 threads added to thread pool process diagram

4. Summary:

1. Generate thread pool as needed;

2. Class implements the Run method in runnable;

3. Submit the task using execute or Submit method;

4. Apply shutdown () to close the resource when all threads of the thread pool have finished executing and no longer need the thread pool.

"Java Thread pool Quick Learning Tutorial"

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.