Java Multithreading (quad), thread pool

Source: Internet
Author: User

Java Multithreading (quad), thread poolCategory: Javase comprehensive knowledge points 2012-09-19 17:46 3943 people reading reviews (1) favorite reports

The cost of starting a new thread is relatively high because it involves interacting with the operating system. In this case, the use of the thread pool provides a good performance, especially if you need to consider the use of threading pools when you want to create a lot of short-lived threads in your program.

Similar to the database connection pool, the thread pool creates a large number of idle threads at system startup, the program passes a Runnable object to the thread pool, and the thread pool initiates a thread to execute the object's Run method, and when the Run method finishes execution, it does not die. Instead, return to the thread pool to become idle, waiting to execute the next Runnable object's Run method.

In addition, the use of the thread pool can effectively control the number of concurrent threads in the system, but when the system contains a large number of concurrent threads, the system performance will be severely degraded, even causing the JVM to crash. The maximum thread count parameter of the thread pool can control the number of concurrent threads in the system.

Before JDK1.5, developers had to implement their own thread pool manually, and Java built-in support for thread pooling after JDK1.5.

All supported classes that are concurrent with multithreading are in the Java.lang.concurrent package. We can use the class inside to control the execution of multithreading more.

First, executors class

The Executors factory class is provided in JDK1.5 to generate the connection pool, which contains several static engineering methods to create the connection pool:

1, public static executorservice newfixedthreadpool (int nthreads): Create a reusable thread pool with a fixed number of threads.

2, public static Executorservice Newsinglethreadexecutor (): Create a thread pool that is only single thread, it is equivalent to Newfixedthreadpool method is passed the parameter is 1

3, public static Executorservice Newcachedthreadpool (): Create a thread pool with caching capabilities, the system creates threads as needed, and these threads are cached in the thread pool.

4, public static Scheduledexecutorservice newsinglethreadscheduledexecutor: Create a thread pool with only one threads, he can perform thread tasks after specifying a delay

5. public static scheduledexecutorservice newscheduledthreadpool (int corepoolsize): Creates a thread pool with the specified number of threads, which can then specify the deferred execution of the threading task. Corepoolsize refers to the number of threads held in the pool, even if the thread is idle and is saved online Cheng.

The above methods have an overloaded method, more than one threadfactory parameter overload method, using less.

Second, Executorservice class

As you can see in the 5 methods above, the return value of the previous 3 methods is a Executorservice object. The Executorservice object represents a thread pool that executes threads as soon as possible (as long as there are idle threads in the thread pool executing the thread task immediately), and the program executes the task as soon as possible by submitting a Runnable object or callable object to that thread pool.

There are several important ways to Executorservice:

Method Summary
 boolean isShutdown()
Returns trueif this executor is closed.
 boolean isTerminated()
Returns trueif all tasks have completed after closing.
 void shutdown()
Starts a sequential shutdown, performs a previously submitted task, but does not accept new tasks.
 List<Runnable> shutdownNow()
An attempt is made to stop all active tasks that are being performed, suspend processing of the awaited task, and return to the list of tasks awaiting execution.
<T> Future<T>
submit(Callable<T> task)
A task that submits a return value is used to execute, returning a future that represents the pending result of the task.
 Future<?> submit(Runnable task)
Submits a Runnable task for execution and returns a future that represents the task.
<T> Future<T>
submit(Runnable task, T result)
Submits a Runnable task for execution and returns a future that represents the task.

Refer to the JDK API documentation in more detail.

The Submit method is a better encapsulation of the Executor interface Execute method, which is recommended using the Submit method.

Third, Scheduleexecutorservice class

In the above 5 methods, the return value of the following 2 methods is a Scheduleexecutorservice object. Scheduleexecutorservice represents a thread pool that can perform thread tasks in a specified deferred or periodic execution.

The Scheduleexecutorservice class is a subclass of the Executorservice class. Therefore, it also has a submit method that submits the task directly, and adds some methods to defer the task processing:

Method Summary
<V> ScheduledFuture<V>
schedule(Callable<V> callable, long delay, TimeUnit unit)
Creates and executes a scheduledfuture that is enabled after a given delay.
 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
Creates and executes a one-time operation that is enabled after a given delay.
 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
Creates and executes a recurring action that is first enabled after a given initial delay, with a given period of time, that is, the execution begins after InitialDelay , then executes after Initialdelay+period , and then InitialDelay + 2 * period after execution, and so on.
 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
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.

Here's a look at the simple use of the thread pool:

1, fixed-size thread pool:

Package Com.tao.test;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public Class Pooltest {public static void main (string[] args) {Executorservice pool=executors.newfixedthreadpool (5);// Create a thread pool for (int i=0;i<7;i++) {pool.submit (New MyThread ()) with a fixed size of 5;} Pool.shutdown ();}} Class MyThread extends thread{    @Override public    void Run () {            System.out.println (Thread.CurrentThread (). GetName () + "executing ... ");    }}
Output Result:
Pool-1-thread-1 is executing ... Pool-1-thread-3 is executing ... Pool-1-thread-2 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-5 is executing ... Pool-1-thread-1 is executing ...
As you can see, we've created 7 mythread thread objects, but because of the size limit of the thread pool, only 5 threads are turned on, which reduces the number of concurrent threads.

2. Single Task thread pool:

public class Pooltest {public static void main (string[] args) {Executorservice pool=executors.newsinglethreadexecutor () ;//Create a single thread pool for (int i=0;i<7;i++) {pool.submit (New MyThread ());} Pool.shutdown ();}}

Output Result:
Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ... Pool-1-thread-1 is executing ...

As you can see, the thread pool opens only one of the threads.

3. Create a variable-size thread pool

public class Pooltest {public static void main (string[] args) {executorservice pool=executors.newcachedthreadpool (); (int i=0;i<5;i++) {Pool.submit (New MyThread ());} Pool.shutdown ();}}

Look at the results of the output:
Pool-1-thread-1 is executing ... Pool-1-thread-3 is executing ... Pool-1-thread-2 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-5 is executing ...

As you can see, we don't limit the size of the thread pool, but it creates threads based on requirements.

4. Delay Thread pool

public class Pooltest {public static void main (string[] args) {Scheduledexecutorservice pool= Executors.newscheduledthreadpool (6); for (int i=0;i<4;i++) {pool.submit (New MyThread ());} Pool.schedule (New MyThread (), timeunit.milliseconds);p ool.schedule (New MyThread (),, Timeunit.milliseconds );p Ool.shutdown ();}}
Output Result:
Pool-1-thread-1 is executing ... Pool-1-thread-3 is executing ... Pool-1-thread-2 is executing ... Pool-1-thread-4 is executing ... Pool-1-thread-6 is executing ... Pool-1-thread-1 is executing ...
As you can see, the last two threads are not executed immediately, but are deferred for 1 seconds.

5. Single Task delay thread pool

public class Pooltest {public static void main (string[] args) {Scheduledexecutorservice pool= Executors.newsinglethreadscheduledexecutor (); for (int i=0;i<4;i++) {pool.submit (New MyThread ());} Pool.schedule (New MyThread (), timeunit.milliseconds);p ool.schedule (New MyThread (),, Timeunit.milliseconds );p Ool.shutdown ();}}

Above we use the JDK to help me encapsulate the thread pool, we can also define the thread pool, view the source code, we found that the excutors inside the static method of getting the thread, internal is called Threadpoolexecutor construction method. Like what:

    public static Executorservice newfixedthreadpool (int nthreads, threadfactory threadfactory) {        return new Threadpoolexecutor (Nthreads, Nthreads,                                      0L, Timeunit.milliseconds,                                      new linkedblockingqueue<runnable> (),                                      threadfactory);    }
As you can see, it returns a thread pool by calling Threadpoolexecutor's construction method. Therefore, we can also manually call Threadpoolexecutor's various construction methods, to define their own thread pool rules, but in general, the use of the thread pool is enough, do not need to implement.

Java Multithreading (quad), thread pool (RPM)

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.