首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

CountDownLatch 计数位零仍然阻塞

2013-01-23 
CountDownLatch计数位0仍然阻塞照书上敲的一个例子,看不出哪里有问题,请教高手:下面程序是用CountDownLatc

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);
    }
}

热点排行