Does the synchronized block always works fine? I am confused now! Am I wrong when using synchronized keyword?
The code snippet is as following:
package com.company;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new MyThread().start();
}
}
}
class MyThread extends Thread {
// no atomic
private static Integer count = 0;
@Override
public void run() {
while (true) {
synchronized (count) {
//synchronized (this) {
if (count > 100)
break;
count++;
System.out.println("ThreadId:" + currentThread().getId() + ","
+ "inc MyThread.count to : " + count);
}
}
}
}
the result is:
ThreadId:10,inc MyThread.count to : 2
ThreadId:9,inc MyThread.count to : 2
ThreadId:9,inc MyThread.count to : 4
ThreadId:9,inc MyThread.count to : 5
ThreadId:9,inc MyThread.count to : 6
....
I don't know why Thread 10 and 9 output the same value.