nevergiveupzeng

导航

newCachedThreadPool线程池

 


public static ExecutorService newCachedThreadPool()创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。调用 execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。因此,长时间保持空闲的线程池不会使用任何资源。注意,可以使用 ThreadPoolExecutor 构造方法创建具有类似属性但细节不同(例如超时参数)的线程池。 

public static ExecutorService newFixedThreadPool(int nThreads)创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。在任意点,在大多数 nThreads 线程会处于处理任务的活动状态。如果在所有线程处于活动状态时提交附加任务,则在有可用线程之前,附加任务将在队列中等待。如果在关闭前的执行期间由于失败而导致任何线程终止,那么一个新线程将代替它执行后续的任务(如果需要)。在某个线程被显式地关闭之前,池中的线程将一直存在。 

新的线程加入后,如果正在运行的线程达到了上限,则会阻塞,直到有了空闲的线程来运行。 
Java代码  收藏代码
  1. import java.util.Random;   
  2. import java.util.concurrent.ExecutorService;   
  3. import java.util.concurrent.Executors;   
  4. import java.util.concurrent.TimeUnit;   
  5.   
  6. /**  
  7. * 线程池newFixedThreadPool的使用。  
  8. *  
  9. */   
  10. public class ExecutorTest {   
  11. public static void main(String args[]) {   
  12. Random random = new Random();   
  13. // 建立一个容量为5的固定尺寸的线程池   
  14. ExecutorService executor = Executors.newFixedThreadPool(5);   
  15. // 判断可是线程池可以结束   
  16. int waitTime = 500;   
  17. for (int i = 0; i < 10; i++) {   
  18. String name = "线程 " + i;   
  19. int time = random.nextInt(1000);   
  20. waitTime += time;   
  21. Runnable runner = new ExecutorThread(name, time);   
  22. System.out.println("增加: " + name + " / " + time);   
  23. executor.execute(runner);   
  24. }   
  25. try {   
  26. Thread.sleep(waitTime);   
  27. executor.shutdown();   
  28. executor.awaitTermination(waitTime, TimeUnit.MILLISECONDS);   
  29. catch (InterruptedException ignored) {   
  30. }   
  31. }   
  32. }   
  33.   
  34. class ExecutorThread implements Runnable {   
  35. private final String name;   
  36. private final int delay;   
  37.   
  38. public ExecutorThread(String name, int delay) {   
  39. this.name = name;   
  40. this.delay = delay;   
  41. }   
  42.   
  43. public void run() {   
  44.   
  45. System.out.println("启动: " + name);   
  46. try {   
  47. Thread.sleep(delay);   
  48. catch (InterruptedException ignored) {   
  49. }   
  50. System.out.println("完成: " + name);   
  51. }   
  52. }  

posted on 2016-03-28 22:13  nevergiveupzeng  阅读(326)  评论(0编辑  收藏  举报