当前位置: 代码迷 >> J2SE >> CountDownLatch 计数位零仍然阻塞
  详细解决方案

CountDownLatch 计数位零仍然阻塞

热度:4402   发布时间:2013-02-25 21:54:08.0
CountDownLatch 计数位0仍然阻塞
照书上敲的一个例子,看不出哪里有问题,请教高手:
下面程序是用CountDownLatch来协调子线程的,但程序运行到begin.wait();的时候,一直处于阻塞状态,想了很久,还找不出原因。

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Runner implements Callable<Integer>{
    private CountDownLatch begin;
    private CountDownLatch end;
    public Runner(CountDownLatch begin,CountDownLatch end)
    {
     this.begin=begin;
     this.end=end;
    }
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
int score=new Random().nextInt(25);
begin.wait();
TimeUnit.MILLISECONDS.sleep(score);
end.countDown();
return score;
}
    public static void main(String[]args) throws InterruptedException, ExecutionException
    {
    
     int num=10;
     CountDownLatch begin=new CountDownLatch(1);
     CountDownLatch end=new CountDownLatch(num);
     ExecutorService es=Executors.newFixedThreadPool(num);
     List<Future<Integer>>futures=new ArrayList<Future<Integer>>();
     for(int i=0;i<num;i++)
     {
     futures.add(es.submit(new Runner(begin,end)));
     }
     begin.countDown();
     System.out.println("ffffffffffffffff");
         end.await();
     int count=0;
     for(Future<Integer>f:futures){
     count+=f.get();
     }
     System.out.println("平均分数为:"+count/num);
    }
}
  相关解决方案