线程池
- 提前创建多个线程放入线程池中,使用时直接获取,使用完直接放入池中;
- 可以避免频繁创建销毁,实现重复利用,类似生活中的公共交通工具。
- 好处:提高相应速度;降低资源消耗;便于线程管理
- API:ExecutorService和Executors
package jingcheng.test.gaoji;import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;//测试线程池
public class TestPool {public static void main(String[] args) {//1、创建服务,创建线程池//newFixedThreadPool参数为线程池大小ExecutorService service = Executors.newFixedThreadPool(10);//执行service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());//2、关闭连接service.shutdown();}}class MyThread implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName());}
}
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-6