Multi-thread pool Executor application, multi-thread executor
After JDK1.5, a built-in thread pool is provided, so that we can better handle thread concurrency issues.
The Executor class allows me to create multiple thread pools:
Create a fixed thread pool Executors. newFixedThreadPool (2)
Create a Variable Buffer thread pool Executors. newCachedThreadPool ()
Create a single thread pool Executors. newSingleThreadExecutor ()
Basic operations on the first interview thread pool:
Package andy. thread. test; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. timeUnit;/*** @ author Zhang, Tianyou * @ version November 8, 2014 6:10:42 */public class ThreadPoolTest {public static void main (String [] args) {// create a fixed thread pool ExecutorService threadPool = Executors. newFixedThreadPool (3); // create a buffer thread pool where new threads can be created as needed // ExecutorService threadP Ool = Executors. newCachedThreadPool (); // after a single thread pool is created, the thread will be restarted after it dies. // ExecutorService threadPool = Executors. newSingleThreadExecutor (); for (int I = 0; I <10; I ++) {final int task = imo-threadpool.exe cute (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubfor (int j = 0; j <= 5; j ++) {try {TimeUnit. SECONDS. sleep (1);} catch (InterruptedException e) {// TODO Auto-generated catch Blocke. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "is looping of" + j + "from task" + task) ;}}}); // start and close the task in sequence and execute the previously submitted task, but do not accept new tasks. ThreadPool. shutdown (); // attempts to stop all ongoing activity tasks, pause processing of pending tasks, and return to the list of tasks awaiting execution. // ThreadPool. shutdownNow (); // Executors every two seconds after the execution thread is scheduled for 6 seconds. newScheduledThreadPool (3 ). scheduleAtFixedRate (new Runnable () {@ Overridepublic void run () {System. out. println ("scheduling .. ") ;}}, 6, 2, TimeUnit. SECONDS );}}
For more information, see the jdk explanation.