线程池
用来统一地管理线程,避免线程的重复创建与销毁。使用线程池可以让执行完的线程回到线程池,等待下一次调用。
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);}