ThreadPoolExecutor在shutdownNow()之后如何判断所有Thread都已经停了?

JiaBaoYu 2009-08-05 10:04:39
我有一个ThreadPoolExecutor,
ThreadPoolExecutor threadPool
= new ThreadPoolExecutor(
0, 10,
60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new ThreadPoolExecutor.DiscardPolicy() );


希望在用户点停止的时候停止所有Thread, 然后提示“STOPPED”:
threadPool.shutdownNow();
while (!threadPool.awaitTermination(5, TimeUnit.SECONDS))
{
System.out.println(threadPool.getActiveCount());
}
System.out.println("STOPPED");


可是一直等不到STOPPED。threadPool.getActiveCount()一直是9

请问是哪出了问题,该如何解决。谢谢!!
...全文
822 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
haizi912168 2011-10-25
  • 打赏
  • 举报
回复
学习了。。。。。
  • 打赏
  • 举报
回复
楼主想想怎么样不满足这一循环条件

while (!threadPool.awaitTermination(5, TimeUnit.SECONDS))


可能只是个参数问题
wlm007007007007 2009-08-05
  • 打赏
  • 举报
回复
路过了啊
wanghf_ 2009-08-05
  • 打赏
  • 举报
回复
我用你的方法做的可以stop,你看一下是不是这样的

public class ThreadTest {

private static int produceTaskSleepTime = 2;

public static void main(String[] args) {
thread();
}

private static void thread(){
try {
// 构造一个线程池
ThreadPoolExecutor producerPool = new ThreadPoolExecutor(2, 6, 4,TimeUnit.SECONDS, new ArrayBlockingQueue(4),new ThreadPoolExecutor.CallerRunsPolicy());

// 每隔produceTaskSleepTime的时间向线程池派送一个任务。
int i=1;
while(!producerPool.awaitTermination(5, TimeUnit.SECONDS)) {
try {
Thread.sleep(produceTaskSleepTime);
String task = "task@ " + i;
System.out.println("put " + task);
producerPool.execute(new ThreadPoolTask(task));
i++;
if(i>5) producerPool.shutdownNow();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("stop");
} catch (Exception e) {

}
}
}






class ThreadPoolTask implements Runnable,Serializable{
private static final long serialVersionUID = 0;
private static int consumeTaskSleepTime = 200;
private Object threadPoolTaskData;

ThreadPoolTask(Object tasks){
this.threadPoolTaskData = tasks;
}

public void run(){
System.out.println("start .."+threadPoolTaskData);
try {
Thread.sleep(consumeTaskSleepTime);
} catch (Exception e) {
e.printStackTrace();
}
threadPoolTaskData=null;
}
}

62,621

社区成员

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

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