Java concurrency tool LockSupport
LockSupport
In the J. U. C framework, there is a class called LockSupport, which can accurately block and wake up specific threads and serve as the primitives of other synchronization classes.
LockSupport includes a park (Object blocker) and an unpark (Object blocker) method for blocking and wakeup, respectively.
For example, the following code contains a thread thread1 and a main thread. In thread1, the park method is called, The unpark method is called in the main thread, and the thread1 status is printed:
import java.util.concurrent.locks.LockSupport;public class Main{ public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println(thread 1 start); LockSupport.park(Thread.currentThread()); try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread 1 end); } }); thread1.start(); System.out.println(main thread start,thread1 +thread1.getState()); Thread.sleep(2000); System.out.println(main thread running,thread1 +thread1.getState()); LockSupport.unpark(thread1); Thread.sleep(6000); System.out.println(main thread end,thread1 +thread1.getState()); }}
Execution result:
Thread 1 start
Main thread start, thread1 RUNNABLE
Main thread running, thread1 WAITING
Thread 1 end
Main thread end, thread1 TERMINATED
As you can see, thread1 becomes WAITTING after the park, and then wake up after the unpark and continue until the execution ends.