ExecutorService:不期望输出

时间:2017-11-10 01:16:47

标签: java runnable executorservice java.util.concurrent

我很难理解输出。在这里,我创建一个执行程序,然后向其提交1000次Runnable任务。预期输出为1000,因为我在synchronized内添加Runable,但实际输出不是,例如,503。任何人都可以帮我解释一下吗? BV

public class FutureTest {

    int count=0;

    public void testExecutor(){
        CountDownLatch counter = new CountDownLatch(1000);
        Runnable incr = ()->{
            //System.out.println("count="+count);
            synchronized(this){
                count++;    
            }
            counter.countDown();

        };
        ExecutorService service = Executors.newFixedThreadPool(10);
        IntStream.range(0, 1000).forEach(i->service.submit(incr));
        counter.await();
        service.shutdown();

        System.out.println(count);
    }


    public static void main(String[] args) {
        new FutureTest().testExecutor();

    }

}

1 个答案:

答案 0 :(得分:2)

您在调用线程中打印出计数,并且在调用计算线程中的所有Runnable代码之前。只需在Runnable中放一个简短的Thread.sleep,就可以看到计数更少了。

public void testExecutor(){
    Runnable incr = ()->{
        //System.out.println("count="+count);
        synchronized(this){
            try {
                Thread.sleep(10);
            catch (InterruptedException e){}
            count++;    
        }
    };

您希望在所有线程完成其操作时使用某些通知,例如倒计时锁定或.awaitTermination(...)

    IntStream.range(0, 1000).forEach(i->service.submit(incr));
    service.shutdown();

    try {
        service.awaitTermination(1000, TimerUnit.SECONDS);
    } catch (InterruptedException e){}

    System.out.println(count);