Why n sometimes equals 1 or 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);
}
Shouldn't the increment method only allow one thread to execute it at any given moment?
Maybe it is the debugger, it seems that when I run it normally I always get 2 but when i debug the code it some times return 1.
t1.start();in thet2run method.staticthread instances?. even if the thread instances weren't static, he would still end up with the same unpredictable behaviour . right?mainmethod?