Java notes -- Use thread pool to optimize multi-thread programming
Using thread pool optimization multi-thread programming to understand the thread pool in Java, all objects need to be created through the new operator. If you create a large number of objects with short lifecycles, the performance of the entire program will be very low. In this case, we need to use the pool technology, such as the database connection pool and thread pool. After java, java comes with a thread pool, and a concurrent package is added under the util package. This package mainly describes how to use java threads and thread pools. The Executor, ExecutorService, ScheduledExecutorService, ThreadFactoryScheduledExecutorService, ThreadFactory, and Callable classes are defined in the Executors class under the java. util. concurrent package. This class supports the following methods: a. Create and return the method of setting ExecutorService with common configuration strings. B. Create and return the method of setting ScheduledExecutorService with common configuration strings. C. Create and return the "encapsulated" ExecutorService method, which disables reconfiguration by making implementation-specific methods inaccessible. D. Create and return the ThreadFactory method. It can set the newly created thread to a known state. E. Create and return Callable methods in non-closure form, so that they can be used in the execution method that requires Callable. -- If you want To reprint this article, please indicate the reprinted address "http://www.cnblogs.com/XHJT/p/3897773.html" thank you -- first we will first compare to use the thread pool to create multiple threads and use the independent way to create multiple threads difference, here we will explain the necessity and importance of the thread pool by comparing two methods to occupy memory and time consumption. Code example: copy the code package com. xhj. thread; import java. util. concurrent. executorService; import java. util. concurrent. executors; /*** compare the advantages and disadvantages of independent creation and thread pool creation threads -- time and memory occupation ** @ author XIEHEJUN **/public class CompareThreadPool implements Runnable {private int id = 0; @ Override public void run () {id ++;} public static void main (String [] args) {/*** create 1000 threads independently */{// obtain the object Runtime run = Runtime when the current program is running. getRunti Me (); // call the garbage collection mechanism to reduce memory error run. gc (); // get the idle memory of the current JVM long freeMemory = run. freeMemory (); // The current System time long timePro = System. currentTimeMillis (); // independently created and executed 1000 threads for (int I = 0; I <1000; I ++) {new Thread (new CompareThreadPool ()). start ();} System. out. println ("memory size required to create and execute 1000 threads independently:" + (freeMemory-run. freeMemory (); System. out. println ("the time required to create and run 1000 threads independently is:" + (System. currentTimeMillis ()-t ImePro);}/*** create 1000 threads using the thread pool */{// obtain the Runtime run = Runtime object when the current program is running. getRuntime (); // call the garbage collection mechanism to reduce memory error run. gc (); // get the idle memory of the current JVM long freeMemory = run. freeMemory (); // The current System time long timePro = System. currentTimeMillis (); ExecutorService service = Executors. newFixedThreadPool (2); // independently created and executed 1000 threads for (int I = 0; I <1000; I ++) {service. submit (new CompareThreadPool ();} System. out. println ("user line Memory size required to create 1000 threads in the thread pool: "+ (freeMemory-run. freeMemory (); // The thread pool is used completely, and the thread pool service is disabled. shutdown (); System. out. println ("the time required to create and run 1000 threads using the thread pool is:" + (System. currentTimeMillis ()-timePro) ;}} the result of copying the code is: conclusion -- Why use the thread pool: Through the above example, we know that using the thread pool can greatly improve the system performance, this improves the execution efficiency of program tasks and saves the system memory space. In the thread pool, each worker thread can be reused to execute multiple tasks, reducing the number of threads created and destroyed. The number of threads can be adjusted according to the system's capacity, so that the system can achieve the best running effect. Thread Pool Principle: A thread pool has multiple running threads. When a Runnable or Callable interface object is added to the thread pool, a thread executes run () method or call () method. If the method execution is complete, the thread does not terminate. Instead, the thread continues to be runable in the pool to run new tasks. Understand the thread pool (several common static methods for creating a thread pool in java). in java, the top-level interface of the thread pool is util. executors tool class under the concurrent package, in which many methods to operate the thread pool are defined. Among them, the most common thread pools are: 1. create a single thread pool: newSingleThreadExecutor (). Create a thread pool with only one thread. This single thread executes all tasks in the task submission order. If an exception is interrupted, the thread pool will re-establish a single thread to replace it for subsequent work. Code instance: copy the code/*** to create a single-threaded thread pool ** @ return */public ExecutorService SingleThreadPool () {ExecutorService singlePool = Executors. newSingleThreadExecutor (); return singlePool;} copy Code 2. create a cacheable thread pool: newCachedThreadPool (). Create a thread pool with no limited size and can only be used. It will open up and reduce memory space based on the number of tasks, however, the thread size in the thread pool depends on the system performance or JVM capacity code instance: copy the code/*** create a cache thread pool ** @ return */public ExecutorService CachedThreadPool () {ExecutorService cachedPool = Executors. newCachedThreadPool (); return cachedPool;} copy code 3. create a fixed-size thread pool: newFixedThreadPool () to create a fixed-size thread pool. When a task is submitted, a thread is created until the thread size reaches the maximum value allowed by the thread pool. If a thread ends, the thread pool adds a new thread. Code instance: copy the code/*** to create a fixed-size thread pool ** @ return */public ExecutorService FixedThreadPool () {ExecutorService fixedPool = Executors. newFixedThreadPool (2); return fixedPool;} copy code 4. create a thread pool newScheduledThreadPool () that can be scheduled and periodically executed, and create a thread pool that can be scheduled and periodically executed. The thread pool has no size limit to implement periodic task scheduling. Code example: ScheduledThreadPoolExecutor scheduledPool = new ScheduledThreadPoolExecutor: copy the code package com. xhj. thread; import java. util. imports; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. scheduledThreadPoolExecutor; import java. util. concurrent. timeUnit;/*** understanding and application of several common thread pools ** @ author XIEHEJU N **/public class CreateThreadPools extends Thread {@ Override public void run () {System. out. println ("System time:" + System. currentTimeMillis () + "Thread:" + Thread. currentThread (). getName () + "running !! ");}/*** Create a single-threaded thread pool ** @ return */public ExecutorService SingleThreadPool () {ExecutorService singlePool = Executors. newSingleThreadExecutor (); return singlePool;}/*** create a fixed-size thread pool ** @ return */public ExecutorService FixedThreadPool () {ExecutorService fixedPool = Executors. newFixedThreadPool (3); return fixedPool;}/*** create a cache thread pool ** @ return */public ExecutorService CachedThreadPool () {ExecutorService cachedPool = Executors. newCachedThreadPool (); return cachedPool;}/*** put the created thread into the thread pool and execute ** @ param pool */public void service (ExecutorService pool) {// create Thread thread1 = new CreateThreadPools (); Thread thread2 = new CreateThreadPools (); Thread thread3 = new CreateThreadPools (); Thread thread4 = new CreateThreadPools (); thread thread5 = new CreateThreadPools (); // The Thread enters the Thread pool and runs pool.exe cute (thread1); pool.exe cute (thread2); pool.exe cute (thread3 ); pool.exe cute (thread4); pool.exe cute (thread5); // close the thread pool. shutdown ();}/*** create a thread pool of unlimited size, available with scheduled and periodic Services */public void scheduledThreadPool () {ScheduledThreadPoolExecutor scheduledPool = new ScheduledThreadPoolExecutor (1 ); scheduledPool. scheduleAtFixedRate (new Runnable () {@ Override public void run () {System. out. println ("=======" + System. currentTimeMillis () + "========") ;}}, 1000,500 0, TimeUnit. MILLISECONDS); scheduledPool. scheduleAtFixedRate (new Runnable () {@ Override public void run () {System. out. println (System. nanoTime (); }}, 1000,200 0, TimeUnit. MILLISECONDS);} public static void main (String [] args) {CreateThreadPools creatThreadPool = new CreateThreadPools (); interval SC = new Queue (System. in); while (true) {System. out. println ("select create thread pool: 1. single thread pool; 2. cache thread pool; 3. fixed thread pool; 4 Periodical thread pool "); int I = SC. nextInt (); switch (I) {case 1: System. out. println ("----- call the thread pool of a single thread -----"); // call the creatThreadPool of a single thread. service (creatThreadPool. singleThreadPool (); break; case 2: System. out. println ("----- call the thread pool of the cacheable thread -----"); // call the creatThreadPool of the thread pool of the cacheable thread. service (creatThreadPool. cachedThreadPool (); break; case 3: System. out. println ("----- call the thread pool of a fixed-size thread -----"); // call the creatThreadPool of a fixed-size thread. service (creatThreadPool. fixedThreadPool (); break; case 4: System. out. println ("----- thread pool with unlimited call sizes and can be set and periodically executed -----"); // call the creatThreadPool of a fixed-size thread. scheduledThreadPool (); break ;}}}}