Java thread Lock uses Condition to implement thread waiting (await) and notification (signal)

The java.util.concurrent.locks.ReentrantLock lock of JDK1.5, JDK also provides us with the class java.util.concurrent.locks.Condition corresponding to this function. Condition and reentrant locks generate a Condtion instance bound to the current reentrant lock through the lock.newCondition() method, and we notify the instance to control the thread's waiting and notification.

package com.jalja.org.base.Thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition cooperates with Lock to realize thread waiting and notification
 */
public class ConditionTest{
    public static ReentrantLock lock=new ReentrantLock();
    public static Condition condition =lock.newCondition();
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                lock.lock();//Request lock
                try{
                    System.out.println(Thread.currentThread().getName()+"=="Enter waiting");
                    condition.await();//Set the current thread to wait
                }catch (InterruptedException e) {
                    e.printStackTrace ();
                }finally{
                    lock.unlock();//Release the lock
                }
                System.out.println(Thread.currentThread().getName()+"=="Continue to execute");
            }    
        }.start();
        new Thread(){
            @Override
            public void run() {
                lock.lock();//Request lock
                try{
                    System.out.println(Thread.currentThread().getName()+"=》进入");
                    Thread.sleep(2000);//rest for 2 seconds
                    condition.signal();//Randomly wake up a thread in the waiting queue
                    System.out.println(Thread.currentThread().getName()+"break end");
                }catch (InterruptedException e) {
                    e.printStackTrace ();
                }finally{
                    lock.unlock();//Release the lock
                }
            }    
        }.start();
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326470256&siteId=291194637