Java SE5的java.util.concurrent包中的执行器(Executor)用来管理Thread对象,从而简化并发编程。
关灯线程:
public class LiftOffThread implements Runnable {
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOffThread() {
}
public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff") + ")";
}
@Override
public void run() {
while (countDown-- > 0) {
System.out.println(status());
}
}
}
使用Excutor一:
ExecutorService mService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
mService.execute(new LiftOffThread());
}
mService.shutdown();
运行结果:
使用Excutor二:
//预先分配线程数
ExecutorService mService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
mService.execute(new LiftOffThread());
}
mService.shutdown();
运行结果:
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-13 04:19:43