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 create new threads as needed//Executorservice ThreadPool = Executors.newcachedthreadpool ();//create a single thread pool when threads die and will reboot// 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, performs a previously submitted task, but does not accept new tasks. Threadpool.shutdown ();//try to stop all positiveIn the active task that executes, pauses processing of the awaited task and returns a list of tasks waiting to be executed. Threadpool.shutdownnow ();//The execution of a thread is scheduled to execute once every 2 seconds after 6 seconds of execution Executors.newscheduledthreadpool (3). Scheduleatfixedrate (New Runnable () {@Overridepublic void run () {System.out.println ("dispatched: ");}}, 6, 2, timeunit.seconds);}}
Read more about JDK explanations.
Multi-thread thread pool executor application