java线程池

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 stub

		ExecutorService 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:任务完毕



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值