- 背景:经常创建和销毁、使用量比较大的资源,比如并发情况下的线程,对性能影响很大。
- 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完后放回池中。可以避免频繁创建销毁、实现重复利用。
- 线程池能够提高响应时间,减少创建新线程的时间;降低资源消耗;便于进程管理。
JDK 5.0起提供了线程池的相关API:ExecutorService
和Executors
ExecutorService
:真正的线程池接口。常见子类ThreadPoolExecutor
- void execute(Runnable command):执行任务/指令,没有返回值,一般用来执行Runnable
- void shutdown():关闭线程池
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池。
例:
package syn;
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());
//2、关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}