Java Multithreading (iv), thread pool __java

Source: Internet
Author: User

The cost of starting a new thread is relatively high because it involves interacting with the operating system. In this case, using a thread pool provides a good performance, especially when you need to create a large number of short-lived threads in your program, and you should consider using a pool of threads.

Similar to database connection pooling, the thread pool creates a large number of idle threads when the system starts up, and the program passes a Runnable object to the thread pool, which initiates a thread to execute the object's Run method, which does not die when execution of the Run method is completed. Instead, it returns to the Run method that is idle in the thread pool and waits for the next Runnable object to be executed.

In addition, the use of a 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 is drastically degraded and even the JVM crashes. The maximum number of thread pool parameters can control the number of concurrent threads in the system.

Prior to JDK1.5, the developer had to manually implement its own thread pool, and after the JDK1.5, the Java built in to support the threads pools.

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


First, executors class

JDK1.5 provides a executors factory class to generate connection pools, which contain several static engineering methods to create connection pools:

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 single thread pool, which is equivalent to the Newfixedthreadpool method is passed the parameter is 1

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

4. public static Scheduledexecutorservice Newsinglethreadscheduledexecutor: Create a thread pool with only one threads, and he can perform a thread task after specifying a delay

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

Several of the above methods have an overloaded method that passes in more than one overloaded method of threadfactory parameters, and uses 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 to perform the thread task immediately), and the program simply commits a Runnable object or callable object to the thread pool, and the thread executes the task as soon as possible.

There are several important ways to Executorservice:

Method Summary
Boolean IsShutDown ()
Returns true if this executor is closed.
Boolean isterminated ()
Returns true if all tasks have been completed after the shutdown.
void shutdown ()
Initiates a sequential shutdown, performs a previously committed task, but does not accept new tasks.
List<runnable> Shutdownnow ()
An attempt was made to stop all active tasks, suspend processing of waiting tasks, and return a list of tasks waiting to be executed.
<T> future<t>
Submit (callable<t> Task)
A task that submits a return value is used for execution, returning a Future that represents the pending result of the task.
Future<?> Submit (Runnable Task)
Commits a Runnable task to execute, and returns a Future that represents the task.
<T> future<t>
Submit (Runnable task, T result)
Commits a Runnable task to execute, 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, and it is recommended that the Submit method be used.


Third, Scheduleexecutorservice class

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

The Scheduleexecutorservice class is a subclass of the Executorservice class. As a result, it also has a submit method for submitting tasks directly, and there are new ways to delay 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 periodic operation that was 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, followed by InitialDelay + 2 * Period After execution, and so forth.
Scheduledfuture<?> Schedulewithfixeddelay (Runnable command, long initialdelay, long delay, timeunit unit)
Creates and executes a periodic operation that was first enabled after a given initial delay, followed by a given delay between execution termination and the start of the next execution.


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


1, fixed size of the thread pool:[Java]  View plain  copy 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 with a fixed size of 5             for (int i=0;i<7;i++) {                pool.submit (New mythread ());            }           pool.shutdown ();       }  }   class mythread extends thread{        @Override  &nbsP     public void run ()  {                system.out.println (Thread.CurrentThread (). GetName () + "executing ... ");       }  }   Output results:[Java]View Plain Copy

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.