Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ExecutorService:不需要输出_Java_Runnable_Executorservice_Java.util.concurrent - Fatal编程技术网

Java ExecutorService:不需要输出

Java ExecutorService:不需要输出,java,runnable,executorservice,java.util.concurrent,Java,Runnable,Executorservice,Java.util.concurrent,我很难理解输出。在这里,我创建了一个执行器,然后将Runnable任务提交给它1000次。预期的输出是1000,因为我在可运行的中添加了同步的,但实际的输出不是,例如503。谁能帮我解释一下吗?bv public class FutureTest { int count=0; public void testExecutor(){ CountDownLatch counter = new CountDownLatch(1000); Runnab

我很难理解输出。在这里,我创建了一个执行器,然后将
Runnable
任务提交给它1000次。预期的输出是1000,因为我在
可运行的
中添加了
同步的
,但实际的输出不是,例如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();

    }

}

您正在打印调用线程中的计数,并且在调用计算线程中的所有可运行代码之前。只要放一个短线程。在你的Runnable中睡眠,就可以看到计数更少

public void testExecutor(){
    Runnable incr = ()->{
        //System.out.println("count="+count);
        synchronized(this){
            try {
                Thread.sleep(10);
            catch (InterruptedException e){}
            count++;    
        }
    };
您需要在所有线程完成其操作时使用一些通知,例如倒计时闩锁或
.awaitTermination(…)


在所有线程完成之前打印出计数。你需要一个倒计时锁,只需在Runnable中添加一个
线程。sleep(10)
,就可以明白我的意思。那么伯爵是0@NathanHughes,这里
这个
是在main方法中创建的
new FutureTest()
。@Nathanhughs:从用于同步的
这个
中打印出
hashCode()
,它们都是相同的对象,所以他的同步锁实际上是正确的。谢谢。我添加了倒数锁存器,现在就可以了。
    IntStream.range(0, 1000).forEach(i->service.submit(incr));
    service.shutdown();

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

    System.out.println(count);