使用Executor管理Thread对象总是抛出异常

Love_XH 2009-10-28 02:26:14
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)
...全文
127 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
冰思雨 2009-10-30
  • 打赏
  • 举报
回复
顶楼上的
islandrabbit 2009-10-30
  • 打赏
  • 举报
回复
请看下面代码注释:

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(); //这一行要去掉,不然下个循环就会出现java.util.concurrent.RejectedExecutionException. 因为exec已经shutdown了。
System.out.println("等待发射...");
}
exec.shutdown(); //把那行代码移到循环外
}

}

lz12366007 2009-10-30
  • 打赏
  • 举报
回复
帮顶下。。手下没eclipse!!看不出来!!
lyre129 2009-10-30
  • 打赏
  • 举报
回复
也不会,期待解答!

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧