ExecutorService测试03

package t1;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThread15 {

public static void main(String[] args) {
// 1. newFixedThreadPool:创建固定大小的线程池
// 2. newCachedThreadPool:创建可缓存线程池,当线程池中的线程空闲时间超过60s,便会终止该空闲线程并从缓存线程池中移除
// 3. newSingleThreadExecutor,创建单线程的线程池
// 4. newScheduledThreadPool,创建固定大小且能够执行定时或周期性任务的线程池
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
final int index = i;

// try {
// Thread.sleep(index * 100);
// } catch (Exception e) {
// e.printStackTrace();
// }

//如果给线程执行完成后、线程会被回收等待下次任务,此时不会创建新的线程。

//如果线程不不足以应对任务,会创建新的线程。

// 使用newCachedThreadPool的时候要根据实际任务运行时间情况,
// 因为它可以创建最多Integer.MAX_VALUE个线程,反而会占用系统资源,
// 降低运行效率。这就是为什么官方文档中会说:
// newCachedThreadPool会大幅度提高大量短暂异步任务的性能了

es.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ":newCachedThreadPool");
}
});
}
}

}

执行结果:

线程执行完成后,所有线程再等待60秒,程序才结束。

pool-1-thread-1:newCachedThreadPool
pool-1-thread-3:newCachedThreadPool
pool-1-thread-2:newCachedThreadPool
pool-1-thread-4:newCachedThreadPool
pool-1-thread-6:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-4:newCachedThreadPool
pool-1-thread-6:newCachedThreadPool
pool-1-thread-2:newCachedThreadPool
pool-1-thread-5:newCachedThreadPool

 

执行结果:

线程执行完成后,所有线程再等待60秒,程序才结束。

pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool
pool-1-thread-1:newCachedThreadPool

posted @ 2020-03-31 15:32  工设091  阅读(100)  评论(0)    收藏  举报