我很难理解输出。这里我创建了一个执行器,然后向它提交一个 Runnable
任务 1000 次。预期输出是 1000,因为我在 Runable
内部添加了 synchronized
,但实际输出不是,例如 503。任何人都可以帮我解释一下吗?
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 中放置一个简短的 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);
关于java - ExecutorService:输出不是预期的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47214262/