Почему в данном случае, когда первый поток new Thread(testThread) входит в свой run(), а далее в synchronized блок, он не блокирует mutex у общего ресурса, т.е. Solution.x, для двух разных потоков new Thread(testThread) и new Thread(testThread1). Почему сначала не выполняется блок в run() в TestThread, а уже затем, когда mutex у Solution.x освобождается, TestThread1 его захватывает и продолжает свою работу в своём run()?
public class Solution {
public static void main(String[] args) throws ParseException {
TestThread testThread = new TestThread();
TestThread1 testThread1 = new TestThread1();
new Thread(testThread, "testThread").start();
new Thread(testThread1, "testThread1").start();
}
public volatile static Integer x = 0;
public static class TestThread implements Runnable {
@Override
public void run() {
synchronized (Solution.x) {
for (int i = 0; i < 10; i++) {
Solution.x++;
System.out.println(Solution.x + " " + Thread.currentThread().getName());
}
}
}
}
public static class TestThread1 implements Runnable {
@Override
public void run() {
synchronized (Solution.x) {
for (int i = 0; i < 10; i++) {
Solution.x--;
System.out.println(Solution.x + " " + Thread.currentThread().getName());
}
}
}
}
}
Ожидаемый вывод:
0 testThread
1 testThread
2 testThread
3 testThread
4 testThread
5 testThread
6 testThread
7 testThread
8 testThread
9 testThread
10 testThread
9 testThread1
8 testThread1
7 testThread1
6 testThread1
5 testThread1
4 testThread1
3 testThread1
2 testThread1
1 testThread1
0 testThread1
Process finished with exit code 0
Фактический вывод:
1 testThread
1 testThread
0 testThread1
2 testThread
1 testThread1
2 testThread
1 testThread1
2 testThread
1 testThread1
2 testThread
1 testThread1
2 testThread
1 testThread1
2 testThread
1 testThread1
1 testThread1
0 testThread1
2 testThread
-1 testThread1
0 testThread
Process finished with exit code 0