使用线程池与非线程池的区别

末蓝、 2022-02-01 03:11 482阅读 0赞

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

//线程池和非线程池的区别
public class ThreadPool {

  1. public static int times = 100;//100,1000,10000
  2. public static ArrayBlockingQueue arrayWorkQueue = new ArrayBlockingQueue(1000);
  3. public static ExecutorService threadPool = new ThreadPoolExecutor(5, //corePoolSize线程池中核心线程数
  4. 10,
  5. 60,
  6. TimeUnit.SECONDS,
  7. arrayWorkQueue,
  8. new ThreadPoolExecutor.DiscardOldestPolicy()
  9. );
  10. public static void useThreadPool() \{
  11. Long start = System.currentTimeMillis();
  12. for (int i = 0; i < times; i++) \{
  13. threadPool.execute(new Runnable() \{
  14. public void run() \{
  15. System.out.println("说点什么吧...");
  16. \}
  17. \});
  18. \}
  19. threadPool.shutdown();
  20. while (true) \{
  21. if (threadPool.isTerminated()) \{
  22. Long end = System.currentTimeMillis();
  23. System.out.println(end - start);
  24. break;
  25. \}
  26. \}
  27. \}
  28. public static void createNewThread() \{
  29. Long start = System.currentTimeMillis();
  30. for (int i = 0; i < times; i++) \{
  31. new Thread() \{
  32. public void run() \{
  33. System.out.println("说点什么吧...");
  34. \}
  35. \}.start();
  36. \}
  37. Long end = System.currentTimeMillis();
  38. System.out.println(end - start);
  39. \}
  40. public static void main(String args\[\]) \{
  41. createNewThread();
  42. //useThreadPool();
  43. \}

}

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


























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

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

非线程池的缺点

  • 每次创建性能消耗大
  • 无序,缺乏管理。容易无限制创建线程,引起OOM和死机

发表评论

表情:
评论列表 (有 0 条评论,482人围观)

还没有评论,来说两句吧...

相关阅读

    相关 tomcat线原生线比较

              jdk提供的线程池,当核心线程数已满,但是最大线程池数未满,来一个任务时,会先将任务加入阻塞队列。队列满之后才会创建线程来处理任务,这是比较适合cpu密集型