Java thread (17): new feature-Thread Pool

Source: Internet
Author: User

Sun has made a lot of extensions to Java Thread class libraries in Java 5. Among them, the thread pool is one of the new features of Java 5. Besides the thread pool, there are also a lot of multithreading-related content, it brings great convenience to multi-threaded programming. To write efficient, stable, and reliable multi-threaded programs, it is particularly important to add content to the thread section. All content about the new features of java 5 threads is under java. util. concurrent, which contains a large number of interfaces and classes. familiarity with these API features is a difficult learning process. At present, there are few materials and books related to this aspect. Books about thread are still on the knowledge level before Java 5. Of course, the new feature does not have to do with multi-threaded programs. Before Java 5, you can write excellent multi-threaded programs. The price is different. The basic idea of the thread pool is also the idea of an object pool, which opens up a piece of memory space and stores a large number of threads (not dead). The thread execution scheduling in the pool is handled by the pool manager. When there is a thread task, take one from the pool. After the execution is complete, the thread object is returned to the pool. This avoids the performance overhead caused by repeated creation of thread objects and saves system resources. Before Java 5, it is quite difficult to implement a thread pool. Now Java 5 has done everything for us, and we only need to use it according to the provided API, you can enjoy the great convenience brought by the thread pool. Java 5 thread pools are divided into various types: fixed-size thread pools, variable-size connection pools, and ,. Before using the thread pool, you must know how to create a thread pool. in java 5, you must understand java. util. concurrent. executors class API. This class provides a large number of static methods for creating connection pools. 1. fixed-size thread pool import java. util. concurrent. executors; import java. util. concurrent. executorService;/*** Java thread: Thread Pool-** @ author Administrator 23:30:44 */public class Test {public static void main (String [] args) {// create a thread pool that can reuse a fixed number of threads ExecutorService pool = Executors. newFixedThreadPool (2); // creates and implements the Runnable interface object. Of course, the Thread object also implements the Runnable interface Thread t1 = new MyThread (); Thread t2 = new MyThread (); Th Read t3 = new MyThread (); Thread t4 = new MyThread (); Thread t5 = new MyThread (); // put the Thread into the pool and execute pool.exe cute (t1 ); pool.exe cute (t2); pool.exe cute (t3); pool.exe cute (t4); pool.exe cute (t5); // close the thread pool. shutdown () ;}} class MyThread extends Thread {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + "running... ") ;}} Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-2 is being executed... Process finished with exit code 0 II. code for creating a pool object in a row based on the previous example of a single task thread pool: // create an Executor using a single worker thread, run this thread in the unbounded queue mode. ExecutorService pool = Executors. newSingleThreadExecutor (); the output result is: pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Process finished with exit code 0 for the above two connection pools, the size is fixed, when the thread (or task) of the pool to be added exceeds the maximum size of the pool, the thread pool needs to wait in queue. Once there are threads in the pool, a thread waiting in queue will be executed in the pool. 3. The variable-size thread pool is similar to the above, but the method for creating the pool is changed: // create a thread pool that can create a new thread as needed, but they will be reused when previously constructed threads are available. ExecutorService pool = Executors. newCachedThreadPool (); pool-1-thread-5 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-4 is being executed... Pool-1-thread-3 is being executed... Pool-1-thread-2 is being executed... Process finished with exit code 0 4. Delay connection pool import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit;/*** Java thread: Thread Pool-** @ author Administrator 23:30:44 */public class Test {public static void main (String [] args) {// create a thread pool that can be scheduled to run commands or periodically after a given delay. ScheduledExecutorService pool = Executors. newScheduledThreadPool (2); // creates and implements the Runnable interface object. Of course, the Thread object also implements the Runnable interface Thread t1 = new MyThread (); Thread t2 = new MyThread (); thread t3 = new MyThread (); Thread t4 = new MyThread (); Thread t5 = new MyThread (); // put the Thread into the pool and execute pool.exe cute (t1 ); pool.exe cute (t2); pool.exe cute (t3); // use the delayed execution method pool. schedule (t4, 10, TimeUnit. MILLISECONDS); pool. schedule (t5, 10, TimeUnit. MILLISECONDS); // closes the thread pool. shutdown () ;}} class MyThread extends Thread {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + "running... ") ;}} Pool-1-thread-1 is being executed... Pool-1-thread-2 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-2 is being executed... Process finished with exit code 0 V. The single-task delay connection pool is modified based on four codes. // create a single-thread execution program, it can be scheduled to run commands after a given delay or periodically. ScheduledExecutorService pool = Executors. newSingleThreadScheduledExecutor (); pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-1 is being executed... Process finished with exit code 0 VI. Custom thread pool import java. util. concurrent. arrayBlockingQueue; import java. util. concurrent. blockingQueue; import java. util. concurrent. threadPoolExecutor; import java. util. concurrent. timeUnit;/*** Java thread: Thread Pool-custom thread pool ** @ author Administrator 23:30:44 */public class Test {public static void main (String [] args) {// create A waiting queue BlockingQueue <Runnable> bqueue = new RrayBlockingQueue <Runnable> (20); // creates a single-threaded execution program that can be scheduled to run commands or periodically after a given delay. ThreadPoolExecutor pool = new ThreadPoolExecutor (2, 3, 2, TimeUnit. MILLISECONDS, bqueue); // creates and implements the Runnable interface object. Of course, the Thread object also implements the Runnable interface Thread t1 = new MyThread (); Thread t2 = new MyThread (); thread t3 = new MyThread (); Thread t4 = new MyThread (); Thread t5 = new MyThread (); Thread t6 = new MyThread (); Thread t7 = new MyThread (); // put the thread into the pool and execute pool.exe cute (t1); pool.exe cute (t2); pool.exe cute (t3); pool. Execute (t4); pool.exe cute (t5); pool.exe cute (t6); pool.exe cute (t7); // close the thread pool. shutdown () ;}} class MyThread extends Thread {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + "running... "); Try {Thread. sleep (100L);} catch (InterruptedException e) {e. printStackTrace () ;}} pool-1-thread-1 is being executed... Pool-1-thread-2 is being executed... Pool-1-thread-2 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-2 is being executed... Pool-1-thread-1 is being executed... Pool-1-thread-2 is being executed... Process finished with exit code 0 has many constructor methods to create a custom thread pool. In this example, the parameter meanings are as follows: ThreadPoolExecutorpublic ThreadPoolExecutor, blockingQueue <Runnable> workQueue) creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and handler. Using the Executors factory method is much easier than using this General constructor method. Parameter: corePoolSize-Number of threads stored in the pool, including Idle threads. MaximumPoolSize-Maximum number of threads allowed in the pool. KeepAliveTime-when the number of threads exceeds the core, this is the maximum time for Idle threads to wait for new tasks before termination. Unit-keepAliveTime parameter time unit. WorkQueue-the queue used to keep the task before execution. This queue only keeps Runnable tasks submitted by the execute method. Throw: IllegalArgumentException-If corePoolSize or keepAliveTime is smaller than zero, maximumPoolSize is smaller than or equal to zero, or corePoolSize is greater than maximumPoolSize. NullPointerException-If workQueue is null, the custom connection pool is slightly more troublesome, but the ThreadPoolExecutor thread pool object created, you can obtain the size of the current thread pool, the number of threads executing tasks, and the work queue. The content about the Java 5 thread pool is no longer available here. More information needs to be obtained through the API.

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.