Java创建线程中相关线程的编写方式


  本文标签:Java创建线程

Java创建线程一直在不断的进行相关问题的解决,当然我们一直在不断的使用中会有不少的问题出现  。下面我们就先看看如何才能更好的进行相关问题解决  。在上例的基础上改一行创建pool对象的代码为:

创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程  。

  1. ExecutorService pool = Executors.newSingleThreadExecutor();  

创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程  。

  1. ExecutorService pool = Executors.newSingleThreadExecutor();  

输出结果为: 

  1. pool-1-thread-1正在执行  。  。  。   
  2. pool-1-thread-1正在执行  。  。  。   
  3. pool-1-thread-1正在执行  。  。  。   
  4. pool-1-thread-1正在执行  。  。  。   
  5. pool-1-thread-1正在执行  。  。  。   
  6. Process finished with exit code 0   
  7. pool-1-thread-1正在执行  。  。  。   
  8. pool-1-thread-1正在执行  。  。  。   
  9. pool-1-thread-1正在执行  。  。  。   
  10. pool-1-thread-1正在执行  。  。  。   
  11. pool-1-thread-1正在执行  。  。  。   
  12. Process finished with exit code 0  

对于以上两种连接池,大小都是固定的,当要加入的池的线程(或者任务)超过池最大尺寸时候,则入此线程池需要排队等待  。
一旦池中有线程完毕,则排队等待的某个线程会入池执行  。

可变尺寸的线程池

与上面的类似,只是改动下pool的创建方式:

创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们  。

  1. ExecutorService pool = Executors.newCachedThreadPool();  

创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们  。

  1. ExecutorService pool = Executors.newCachedThreadPool();  

Java创建线程代码

  1. pool-1-thread-5正在执行  。  。  。   
  2. pool-1-thread-1正在执行  。  。  。   
  3. pool-1-thread-4正在执行  。  。  。   
  4. pool-1-thread-3正在执行  。  。  。   
  5. pool-1-thread-2正在执行  。  。  。   
  6. Process finished with exit code 0  

以上就是对Java创建线程的详细代码介绍  。