一:使用线程池
①背景:经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
②思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。
③好处:提高响应速度(减少了创建新线程的时间);降低资源消耗(重复利用线程池中线程,不需要每次都创建);便于管理线程
④jdk5.0起提供了线程池相关API:ExecutorService和Executors
A:ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
void execute(Runnable command):执行任务,没有返回值,一般用来执行Runnable
Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
void shutdown():关闭连接池
B:Executors :工具类,线程池的工厂类,用于创建并返回不同类型的线程池。
public class Tread11 {
public static void main(String[] args) {
//创建服务,创建线程池
//newFixedThreadPool 桉树为线程池大小
ExecutorService executorService= Executors.newFixedThreadPool(10);
//执行
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
//关闭
executorService.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
pool-1-thread-2
pool-1-thread-1
pool-1-thread-3
原文:https://www.cnblogs.com/iLisa/p/14727366.html