首页 > 编程语言 > 详细

JDK1.8 创建线程池有哪几种方式?

时间:2021-09-02 02:27:36      阅读:18      评论:0      收藏:0      [点我收藏+]

newFixedThreadPool

定长线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程数量不再变化,当线程发生错误结束时,线程池会补充一个新的线程

测试代码:

技术分享图片
public class TestThreadPool {
 
 //定长线程池,每当提交一个任务就创建一个线程,直到达到线程池的最大数量,这时线程数量不再变化,当线程发生错误结束时,线程池会补充一个新的线程
 static ExecutorService fixedExecutor = Executors.newFixedThreadPool(3);
 
 
 public static void main(String[] args) {
  testFixedExecutor();
 }
 
 //测试定长线程池,线程池的容量为3,提交6个任务,根据打印结果可以看出先执行前3个任务,3个任务结束后再执行后面的任务
 private static void testFixedExecutor() {
  for (int i = 0; i < 6; i++) {
   final int index = i;
   fixedExecutor.execute(new Runnable() {
    public void run() {
     try {
      Thread.sleep(3000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println(Thread.currentThread().getName() + " index:" + index);
    }
   });
  }
  
  try {
   Thread.sleep(4000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("4秒后...");
  
  fixedExecutor.shutdown();
 }
 
}
View Code

打印结果:

pool-1-thread-1 index:0
pool-1-thread-2 index:1
pool-1-thread-3 index:2
4秒后...
pool-1-thread-3 index:5
pool-1-thread-1 index:3
pool-1-thread-2 index:4
  • newCachedThreadPool

可缓存的线程池,如果线程池的容量超过了任务数,自动回收空闲线程,任务增加时可以自动添加新线程,线程池的容量不限制

技术分享图片
public class TestThreadPool {
 
 //可缓存的线程池,如果线程池的容量超过了任务数,自动回收空闲线程,任务增加时可以自动添加新线程,线程池的容量不限制
 static ExecutorService cachedExecutor = Executors.newCachedThreadPool();
 
 
 public static void main(String[] args) {
  testCachedExecutor();
 }
 
 //测试可缓存线程池
 private static void testCachedExecutor() {
  for (int i = 0; i < 6; i++) {
   final int index = i;
   cachedExecutor.execute(new Runnable() {
    public void run() {
     try {
      Thread.sleep(3000);
     } catch (InterruptedException e) {
      e.printStackTrace();
     }
     System.out.println(Thread.currentThread().getName() + " index:" + index);
    }
   });
  }
  
  try {
   Thread.sleep(4000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println("4秒后...");
  
  cachedExecutor.shutdown();
 }
 
}
View Code

打印结果:

pool-1-thread-1 index:0
pool-1-thread-6 index:5
pool-1-thread-5 index:4
pool-1-thread-4 index:3
pool-1-thread-3 index:2
pool-1-thread-2 index:1
4秒后...

https://mp.weixin.qq.com/s/_x8tCnGl7FbQiTKrHTUMWw

JDK1.8 创建线程池有哪几种方式?

原文:https://www.cnblogs.com/luweiweicode/p/15203261.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!