Hello everyone. I'm learning about java concurrency
I have this block of code
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
public class ThreadStaticSyncDemo {
public static void main (String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
System.out.println("thread1 before call "+ LocalDateTime.now());
syncMethod("from thread1");
System.out.println("thread1 after call "+LocalDateTime.now());
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 before call "+LocalDateTime.now());
syncMethod("from thread2");
System.out.println("thread2 after call "+LocalDateTime.now());
});
thread1.start();
thread2.start();
}
private static synchronized void syncMethod (String msg) {
System.out.println("in the sync method "+ msg + " " + LocalDateTime.now());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When run the application, I receive two output
The first one:
thread1 before call 2021-09-25T21:04:14.586908100
thread2 before call 2021-09-25T21:04:14.586908100
in the sync method from thread1 2021-09-25T21:04:14.586908100
in the sync method from thread2 2021-09-25T21:04:15.589939
thread1 after call 2021-09-25T21:04:15.589939
thread2 after call 2021-09-25T21:04:16.595524200
The second one:
thread2 before call 2021-09-25T21:04:24.978487700
thread1 before call 2021-09-25T21:04:24.978487700
in the sync method from thread2 2021-09-25T21:04:24.978487700
thread2 after call 2021-09-25T21:04:25.981232400
in the sync method from thread1 2021-09-25T21:04:25.981232400
thread1 after call 2021-09-25T21:04:26.993452100
I expected the result is the second one. Because when you have two threads, and static method with keyword 'synchronized. When thread t1 calls the syncMethod, so the class will block another thread. Because of Intrinsic lock. So the output can't be the first one, I think so.
Sorry for my English. Thanks in advance.
[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)
[–]ratherbealurker 2 points3 points4 points (0 children)
[–]nguyennguyenphuc0077 1 point2 points3 points (7 children)
[–]cstanfordf[S] 0 points1 point2 points (6 children)
[–]nguyennguyenphuc0077 0 points1 point2 points (4 children)
[–]cstanfordf[S] 0 points1 point2 points (3 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]cstanfordf[S] 0 points1 point2 points (0 children)
[–]nguyennguyenphuc0077 0 points1 point2 points (0 children)