为什么n有时等于1或2
private static int n = 0;
private static Thread t1, t2;
private synchronized static void increment() {
n++;
}
public static void main(String[] args) {
t1 = new Thread(new Runnable() {
public void run() {
increment();
}
});
t2 = new Thread(new Runnable() {
public void run() {
t1.start();
increment();
}
});
t2.start();
try {
t2.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(n);
}
Run Code Online (Sandbox Code Playgroud)
增量方法不应该只允许一个线程在任何给定时刻执行它吗?
也许它是调试器,似乎当我正常运行时我总是得到2但是当我调试代码时它有时会返回1.