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+":任务完毕");
}
}
程序执行结果:
- 执行当前任务的线程为:pool-1-thread-1
- 执行当前任务的线程为:pool-1-thread-2
- pool-1-thread-2:0
- pool-1-thread-1:0
- pool-1-thread-1:1
- pool-1-thread-2:1
- pool-1-thread-1:2
- pool-1-thread-2:2
- pool-1-thread-2:3
- pool-1-thread-1:3
- pool-1-thread-2:4
- pool-1-thread-1:4
- pool-1-thread-1:5
- pool-1-thread-2:5
- pool-1-thread-1:6
- pool-1-thread-2:6
- pool-1-thread-1:7
- pool-1-thread-2:7
- pool-1-thread-2:8
- pool-1-thread-1:8
- pool-1-thread-2:9
- pool-1-thread-1:9
- pool-1-thread-1:任务完毕
- 执行当前任务的线程为:pool-1-thread-1
- pool-1-thread-1:0
- pool-1-thread-2:任务完毕
- 执行当前任务的线程为:pool-1-thread-2
- pool-1-thread-2:0
- pool-1-thread-1:1
- pool-1-thread-2:1
- pool-1-thread-1:2
- pool-1-thread-2:2
- pool-1-thread-1:3
- pool-1-thread-2:3
- pool-1-thread-1:4
- pool-1-thread-2:4
- pool-1-thread-1:5
- pool-1-thread-2:5
- pool-1-thread-1:6
- pool-1-thread-2:6
- pool-1-thread-1:7
- pool-1-thread-2:7
- pool-1-thread-1:8
- pool-1-thread-2:8
- pool-1-thread-1:9
- pool-1-thread-2:9
- pool-1-thread-1:任务完毕
- 执行当前任务的线程为:pool-1-thread-1
- pool-1-thread-1:0
- pool-1-thread-2:任务完毕
- pool-1-thread-1: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
- pool-1-thread-1:7
- pool-1-thread-1:8
- pool-1-thread-1:9
- pool-1-thread-1:任务完毕
170万+

被折叠的 条评论
为什么被折叠?



