Java代码  newCachedThreadPool线程池
  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. }  

相关文章: