- 信号量不用volatile修饰不也可以吗?
- 我写了个信号量的demo如下,去掉volatile也完全可以啊?
public class VolatileDemo1 {
public static volatile boolean inited = false;
public static int var = 0;
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
service.execute(() -> {
try {
TimeUnit.MILLISECONDS.sleep(2);
var = -1;
inited = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
});
service.execute(() -> {
while (!inited) {
System.out.println(var++);
}
System.out.println(var);
});
service.shutdown();
}
}