I ran the following code:
class Counter extends Thread {
static int i=0;
public void run(){
while (true) {
increment();
}
}
public synchronized void increment() {
try {
System.out.println(this.getName() + " " + i++);
wait(1000);
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
Counter c1 = new Counter();
Counter c2 = new Counter();
c1.setName("Thread1");
c2.setName("Thread2");
c1.start();
c2.start();
}
}
As a result of this code, line numbers were added:
1: Thread1 0
2: Thread2 1
3: Thread2 2
4: Thread1 3
5: Thread2 4
6: Thread1 4
7: Thread1 5
8: Thread2 6
stopping...
Since the increment method is synchronized and since it contains wait (1000), I did not expect: 1. Thread2 to print two consecutive fingerprints: lines 2,3 I expected the threads to alternate their fingerprints 2. on lines 5,6, I have 4 .
can someone give me an explanation for this?
source
share