1、为什么要有线程池
线程经常创建和销毁,会消耗特别大的资源,影响性能
2、好处
- 提高响应速度(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理
3、线程池相关API(简单写几个)
- jdk5起,提供了线程池的api:ExecutorService 和 Executors
- ExecutorService :真正的线程池接口,常见子类 ThreadPoolExecutor
- Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
4、代码初识线程池
public class TestPool {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(5);
pool.execute(new MyPool());
pool.execute(new MyPool());
pool.execute(new MyPool());
pool.execute(new MyPool());
// 关闭线程池
pool.shutdown();
}
}
class MyPool implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "running");
}
}
总结:
多线程01-08 线程入门结束 2020年7月21日 晚21:32