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 : "Lift Off !") + ").";
}
public void run(){
while(countDown-- > 0){
System.out.println(status());
Thread.yield();
}
}import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class CachedThreadPool{ public static void main(String[] args){
ExecutorService exec = Executors.newFixedThreadPool(5);
for(int i=0;i<5;i++){
exec.execute(new LiftOff());
exec.shutdown();
System.out.println("等待发射...");
}
}} 异常如下:Exception in thread "main" java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1477)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:384)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:856)
at liftoff.CachedThreadPool.main(CachedThreadPool.java:13)
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 : "Lift Off !") + ").";
}
public void run(){
while(countDown-- > 0){
System.out.println(status());
Thread.yield();
}
}import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class CachedThreadPool{ public static void main(String[] args){
ExecutorService exec = Executors.newFixedThreadPool(5);
for(int i=0;i<5;i++){
exec.execute(new LiftOff());
exec.shutdown();
System.out.println("等待发射...");
}
}} 异常如下:Exception in thread "main" java.util.concurrent.RejectedExecutionException
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1477)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:384)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:856)
at liftoff.CachedThreadPool.main(CachedThreadPool.java:13)
ExecutorService exec = Executors.newFixedThreadPool(5); for(int i=0;i <5;i++){
exec.execute(new LiftOff()); //exec.shutdown(); //这一行要去掉,不然下个循环就会出现java.util.concurrent.RejectedExecutionException. 因为exec已经shutdown了。
System.out.println("等待发射...");
}
exec.shutdown(); //把那行代码移到循环外
} }