赞
踩
目录
三种线程池(返回ThreadPoolExecutor)构造方法
三种线程池(返回ThreadPoolExecutor类)分析
所有实现了ExecutorService接口(Executor的子接口)的实现类都是线程池,可以分为三大类
具体的线程池,在工具类Executors中预创建了六小类
实现了ThreadPoolExecutor类:
实现了ScheduledThreadPoolExecutor类:
实现了ForkJoinPool类:
当然我们也可以自定义线程池
现在有一个任务WorkTask
- public class WorkTask implements Runnable{
- public void run() {
- try {
- int r = (int)(Math.random()*10);
- Thread.sleep(r*1000);
- System.out.println(Thread.currentThread().getId() + " is over");
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
-
- public class CachedThreadPoolTest {
- public static void main(String[] args) {
- ExecutorService exec = Executors.newCachedThreadPool();
- for(int i=0;i<20;i++){
- exec.execute(new WorkTask());
- }
- exec.shutdown();
- }
- }
无界线程池,最多可创建Integer.MAX_VALUE个线程,运行结果没有重复的线程号
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
-
- public class FixedThreadPoolTest {
- public static void main(String[] args) {
- ExecutorService exe
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。