After JDK1.5, we provide our own thread pool so that we can better handle thread concurrency problems.
The executor class provides a way for me to create multiple thread pools:
Create a fixed thread pool Executors.newfixedthreadpool (2)
Creating a variable buffer thread pool Executors.newcachedthreadpool ()
Create a single thread pool Executors.newsinglethreadexecutor ()
Interview the basic operation of the thread pool first:
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 PM 6:10:42 */public class Threadpooltest { public static void Main (string[] args) {//Create a thread pool with a fixed number of threads executorservice ThreadPool = Executors.newfixedthreadpool (3);// Create a buffer thread pool that can be created based on the need to create a new thread//Executorservice ThreadPool = Executors.newcachedthreadpool ();//create a single thread pool when threads die and will start again/ Executorservice ThreadPool = Executors.newsinglethreadexecutor (); for (int i = 0; i <; i++) {final int task = I;threa Dpool.execute (New Runnable () {@Overridepublic void Run () {//TODO auto-generated method stubfor (int j = 0; J <= 5; {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);}});} Starts a sequential shutdown, runs the task that was submitted, but does not accept new tasks. Threadpool.shutdown ();//try to stop allThe active task that is running, pauses processing of the awaited task, and returns a list of tasks that are waiting to run. Threadpool.shutdownnow ();//Run the thread's schedule after 6 seconds to run the Executors.newscheduledthreadpool (3) once every 2 seconds. Scheduleatfixedrate (New Runnable () {@Overridepublic void run () {System.out.println ("dispatched: ");}}, 6, 2, timeunit.seconds);}}
See the JDK explanations for specific information.
Multi-thread thread pool executor application