背景:频繁创建和销毁线程,很消耗资源,对性能影响很大
思路:提前创建好多个线程,放在线程池中,使用时直接获取,用完再放回。可以提高响应速度,避免频繁创建。也可以降低资源消耗,不频繁销毁
变量:corePoolSize:核心池的大小、maximumPoolSize:最大线程数、keepAliveTime:增加的线程在没有任务时最多保持多长时间后终止
public class Xianchengchi {
public static void main(String[] args) {
//1、创建线程池
ExecutorService service = Executors.newFixedThreadPool(3);
//2.执行线程
service.execute(new Mythread());
service.execute(new Mythread());
service.execute(new Mythread());
//3.线程池关闭
service.shutdown();
}
}
class Mythread implements Runnable{
@Override
public void run() {
System.out.println("123");
}
}