我是靠谱客的博主 谦让烧鹅,这篇文章主要介绍使用线程池与非线程池的区别,现在分享给大家,希望可以做个参考。

我们编写一段示例代码,来验证下线程池与非线程池的区别:

//线程池和非线程池的区别
public class ThreadPool {
  
     public static int times = 100;//100,1000,10000
  
     public static ArrayBlockingQueue arrayWorkQueue = new ArrayBlockingQueue(1000);
     public static ExecutorService threadPool = new ThreadPoolExecutor(5, //corePoolSize线程池中核心线程数
             10,
             60,
             TimeUnit.SECONDS,
             arrayWorkQueue,
             new ThreadPoolExecutor.DiscardOldestPolicy()
     );
  
     public static void useThreadPool() {
         Long start = System.currentTimeMillis();
         for (int i = 0; i < times; i++) {
             threadPool.execute(new Runnable() {
                 public void run() {
                     System.out.println("说点什么吧...");
                 }
             });
         }
         threadPool.shutdown();
         while (true) {
             if (threadPool.isTerminated()) {
                 Long end = System.currentTimeMillis();
                 System.out.println(end - start);
                 break;
             }
         }
     }
  
     public static void createNewThread() {
         Long start = System.currentTimeMillis();
         for (int i = 0; i < times; i++) {
  
             new Thread() {
                 public void run() {
                     System.out.println("说点什么吧...");
                 }
             }.start();
         }
         Long end = System.currentTimeMillis();
         System.out.println(end - start);
     }
  
     public static void main(String args[]) {
         createNewThread();
         //useThreadPool();
     }
 }

启动不同数量的线程,然后比较线程池和非线程池的执行结果:

 非线程池线程池
100次16毫秒5ms的
1000次90毫秒28ms
10000次1329ms164ms

结论:不要新的Thread(),采用线程池

非线程池的缺点

  • 每次创建性能消耗大

  • 无序,缺乏管理。容易无限制创建线程,引起OOM和死机

最后

以上就是谦让烧鹅最近收集整理的关于使用线程池与非线程池的区别的全部内容,更多相关使用线程池与非线程池内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部