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

来源:互联网 发布:淘宝订单申请售后时间 编辑:程序博客网 时间:2024/06/13 09:13
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") + ")";}@Overridepublic 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();}}