您的位置:首页 > 编程语言 > Java开发

JAVA编程思想第四版-多线程的练习答案之练习20

2013-11-12 23:00 369 查看
package exercise.exercise20;

public class LiftOff implements Runnable {

protected int countDown = 10;
private static int taskCount = 0;

private final int id = taskCount++;

public LiftOff() {
}

public LiftOff(int countDown) {
this.countDown = countDown;
}

public String status() {
return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff") + ")";
}

@Override
public void run() {
try {
while (countDown-- > 0) {
System.out.println(status());
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("#" + id + " is interrupted!");
}
}

}

package exercise.exercise20;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPool {

/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {//
exec.execute(new LiftOff());
}
Thread.sleep(800);
exec.shutdownNow();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: