您的位置:首页 > 编程语言

通过newCachedThreadPool创建线程代码

2017-10-19 21:05 204 查看
和newFixedThreadPool创建线程代码类似,不同的是通过newCachedThreadPool创建线程代码活跃的线程数目不固定,可以任务多少根据需要创建线程。不必担心关闭问题,因为会自动关闭60s不活动的线程。代码如下:

public class CachedThreadPoolRunner implements Runnable {

private Integer integer;
private long time;

public CachedThreadPoolRunner(Integer integer, long time){
this.integer = integer;
this.time = time;
}

public void run() {

try {
System.out.println(Thread.currentThread().getName() + "执行第" + integer + "个任务");
Thread.sleep(time);
System.out.println(Thread.currentThread().getName() + "执行第" + integer + "个任务结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}


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

public class CachedThreadPoolTest {

public static void main(String[] args) {

ExecutorService executorService = Executors.newCachedThreadPool();
long time = 500;

for (int i = 1; i <= 10 ; i++) {

CachedThreadPoolRunner runner = new CachedThreadPoolRunner(i, time);
System.out.println("准备创建第" + i + "个任务");
executorService.submit(runner);
}

try {
Thread.sleep(time);
executorService.shutdown();
executorService.awaitTermination(time, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


输出的结果为:

准备创建第1个任务
准备创建第2个任务
准备创建第3个任务
pool-1-thread-1执行第1个任务
准备创建第4个任务
pool-1-thread-2执行第2个任务
准备创建第5个任务
pool-1-thread-4执行第4个任务
准备创建第6个任务
pool-1-thread-3执行第3个任务
准备创建第7个任务
pool-1-thread-5执行第5个任务
准备创建第8个任务
pool-1-thread-7执行第7个任务
pool-1-thread-6执行第6个任务
准备创建第9个任务
pool-1-thread-8执行第8个任务
准备创建第10个任务
pool-1-thread-9执行第9个任务
pool-1-thread-10执行第10个任务
pool-1-thread-1执行第1个任务结束
pool-1-thread-2执行第2个任务结束
pool-1-thread-5执行第5个任务结束
pool-1-thread-4执行第4个任务结束
pool-1-thread-9执行第9个任务结束
pool-1-thread-8执行第8个任务结束
pool-1-thread-3执行第3个任务结束
pool-1-thread-7执行第7个任务结束
pool-1-thread-6执行第6个任务结束
pool-1-thread-1
4000
0执行第10个任务结束


可见有10个线程在执行创建的10个任务,这个是跟newFixedThreadPool不同的,newFixedThreadPool只能创建指定数目的线程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程