線程池
?用來統一地管理線程,避免線程的重復創建與銷毀。使用線程池可以讓執行完的線程回到線程池,等待下一次調用。
import jdk.jshell.EvalException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class myTest implements Runnable{public static void main(String[] args) {myTest test = new myTest();ExecutorService service = Executors.newFixedThreadPool(5);for (int i = 0; i < 10; i++) {service.submit(test);}service.shutdown();}@Overridepublic void run() {System.out.println(System.currentTimeMillis()+" ID: "+Thread.currentThread().getId());}
}
線程池的種類
package myTest;import jdk.jshell.EvalException;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class myTest implements Runnable{public static void main(String[] args) {myTest test = new myTest();// 創建一個擁有固定數量的線程池ExecutorService service1 = Executors.newFixedThreadPool(3);// 創建一個只有一個線程的線程池ExecutorService service2 = Executors.newSingleThreadExecutor();// 創建一個擁有自動改變大小的線程池ExecutorService service3 = Executors.newCachedThreadPool();// 創建一個有固定時間執行的單個線程池ExecutorService service4 = Executors.newSingleThreadScheduledExecutor();// 創建一個有固定時間執行的且指定數量的線程池ExecutorService service5 = Executors.newScheduledThreadPool(3);}@Overridepublic void run() {System.out.println(System.currentTimeMillis()+" ID: "+Thread.currentThread().getId());}
}
ThreadPoolExecutor 線程池的內部實現
?我們可以發現線程池的構造方法來源于一個ThreadPoolExecutor類。
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}
?
public ThreadPoolExecutor(// 核心線程池大小int corePoolSize,// 最大線程池大小int maximumPoolSize,// 線程池中超過corePoolSize數目的空閑線程最大存活時間long keepAliveTime,// keepAliveTime時間單位TimeUnit unit,// 阻塞任務隊列BlockingQueue<Runnable> workQueue) {this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);}