java线程池

来源:互联网 发布:java类加载器有哪些 编辑:程序博客网 时间:2024/06/06 06:45
package Thread;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class TestExecutorService {/** * @param args * 使用ExecutorService实现线程池,详细要求如下:1) 线程池要执行的任务为每隔一秒输出一次当前线程的名字,总计输出10次。2) 创建一个线程池,该线程池中只有两个空线程。3) 使线程池执行5次步骤一的任务。 */public static void main(String[] args) {// TODO Auto-generated method stubExecutorService threadPool = Executors.newFixedThreadPool(2);for(int i=0; i<5; i++){Handler handler = new Handler();threadPool.execute(handler);}}}class Handler implements Runnable{public void run(){String name = Thread.currentThread().getName();System.out.println("执行当前任务的线程为:" + name);for(int i=0; i<10; i++){System.out.println(name + ":" + i);try{Thread.sleep(1000);}catch(InterruptedException e){e.printStackTrace();}}System.out.println(name+":任务完毕");}}

程序执行结果:

  1. 执行当前任务的线程为:pool-1-thread-1
  2. 执行当前任务的线程为:pool-1-thread-2
  3. pool-1-thread-2:0
  4. pool-1-thread-1:0
  5. pool-1-thread-1:1
  6. pool-1-thread-2:1
  7. pool-1-thread-1:2
  8. pool-1-thread-2:2
  9. pool-1-thread-2:3
  10. pool-1-thread-1:3
  11. pool-1-thread-2:4
  12. pool-1-thread-1:4
  13. pool-1-thread-1:5
  14. pool-1-thread-2:5
  15. pool-1-thread-1:6
  16. pool-1-thread-2:6
  17. pool-1-thread-1:7
  18. pool-1-thread-2:7
  19. pool-1-thread-2:8
  20. pool-1-thread-1:8
  21. pool-1-thread-2:9
  22. pool-1-thread-1:9
  23. pool-1-thread-1:任务完毕
  24. 执行当前任务的线程为:pool-1-thread-1
  25. pool-1-thread-1:0
  26. pool-1-thread-2:任务完毕
  27. 执行当前任务的线程为:pool-1-thread-2
  28. pool-1-thread-2:0
  29. pool-1-thread-1:1
  30. pool-1-thread-2:1
  31. pool-1-thread-1:2
  32. pool-1-thread-2:2
  33. pool-1-thread-1:3
  34. pool-1-thread-2:3
  35. pool-1-thread-1:4
  36. pool-1-thread-2:4
  37. pool-1-thread-1:5
  38. pool-1-thread-2:5
  39. pool-1-thread-1:6
  40. pool-1-thread-2:6
  41. pool-1-thread-1:7
  42. pool-1-thread-2:7
  43. pool-1-thread-1:8
  44. pool-1-thread-2:8
  45. pool-1-thread-1:9
  46. pool-1-thread-2:9
  47. pool-1-thread-1:任务完毕
  48. 执行当前任务的线程为:pool-1-thread-1
  49. pool-1-thread-1:0
  50. pool-1-thread-2:任务完毕
  51. pool-1-thread-1:1
  52. pool-1-thread-1:2
  53. pool-1-thread-1:3
  54. pool-1-thread-1:4
  55. pool-1-thread-1:5
  56. pool-1-thread-1:6
  57. pool-1-thread-1:7
  58. pool-1-thread-1:8
  59. pool-1-thread-1:9
  60. pool-1-thread-1:任务完毕



0 0
原创粉丝点击