Can anyone explain this code:
public class Main implements Runnable{
private int i;
public synchronized void run() {
System.out.print("i = "+ i +"\n");
if (i % 5 != 0) {
i++;
}
for (int x = 0; x < 5; x++, i++) {
if (x > 1) {
Thread.yield();
}
}
}
public static void main(String[] args) {
Main n = new Main();
for (int x = 100; x > 0; --x) {
new Thread(n).start();
}
}
}
and how the output is
i= 0
i= 5
i= 10
i= 15
i= 20
.
.
.
i= 499
The bottom loop creates 100 threads. Each thread is run immediately, in parallel with the others. In each thread,
Therefore, i is incremented 5 times if it was divisible by 5, and 6 times if it was not. But, the run() method is synchronized. Therefore, no other thread is allowed to execute while one of them is already executing: your program is effectively single-threaded, yield()s are ignored (no other thread can execute), and the output identical to
Remove the synchronized to see all sorts of race-conditions altering the output.