[英]Why isn't my synchronized method working?
Simply put, i'm trying to see the difference when using sychronized keyword over just running a function over threads without locks at all. 简而言之,我正在尝试使用同步关键字而不是在完全没有锁的线程上运行函数时的区别。
In this code: 在此代码中:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class mainClass {
static int count=0;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
Runnable r =new Runnable() {
public synchronized void run() {
count = count + 1;
}
};
IntStream.range(0, 10000)
.forEach(i -> executor.submit(r::run));
executor.shutdown();
System.out.println(count); // 10000
}
}
It doesn't work as i predicated it to work, it returns 10000 in like 40% of the runs. 如我所料,它无法正常工作,它在40%的运行中返回10000。 Why is that?
这是为什么? Where is the problem?
问题出在哪儿? I thought that the function run is being run by only 1 Thread at a time, so there shouldn't be problem, but clearly i'm wrong.
我以为函数运行一次只能由1个线程运行,因此应该没有问题,但显然我错了。
ExecutorService#shutdown
does not wait for tasks to complete. ExecutorService#shutdown
不等待任务完成。 You should use awaitTermination
for that. 您应该
awaitTermination
使用awaitTermination
。
See the documentation for ExecutorService#shutdown . 请参阅ExecutorService#shutdown的文档 。
IntStream.range(0, 10000)
.forEach(i -> executor.submit(r::run));
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTE); // <!-- HERE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.