related articles
- Official website document: https://www.apiref.com/java11-zh/java.base/java/util/concurrent/locks/LockSupport.html
1. Preliminary knowledge
1.1 Why use LockSupport?
3 ways to make threads wait for awakening:
- Use the wait() method in Object to make the thread wait, and use the notify method in Object to wake up the thread
- Use the await() method of Condition in the JUC package to make the thread wait, and use the signal() method to wake up the thread
- The LockSupport class can block the current thread and wake up the specified blocked thread
1.2 Wait() and notify() in the Object class implement thread waiting and awakening
- The wait and notify methods must be used in pairs in a synchronized block or synchronized method. Both wait and notify methods remove the synchronization code block and see the abnormal situation
in the running effect: Exception in thread “A” Exception in thread “B”
java.lang.IllegalMonitorStateException - Wait first and then notify (if you notify first and then wait, another thread will always be waiting)
- Synchronized is a keyword belonging to the JVM level. monitorenter (the bottom layer is done through the monitor object, in fact, wait/notify and other methods also rely on the monitor object to call wait/notify and other methods only in a synchronized block or method)