java中condition对象的await和signal方法使用例子

送外卖和送烟的例子

package com.li.reentrantlock;

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

class MyLock {
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition cigCon = lock.newCondition();
    private static Condition takeCon = lock.newCondition();

    private static boolean hashcig = false;
    private static boolean hastakeout = false;
    public void cigratee(){
        lock.lock();
        try {
            while(!hashcig){
                try {
                    System.out.println("没有烟,歇一会");
                    cigCon.await();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("有烟了,干活");
        }finally {
            lock.unlock();
        }
    }

    public void takeout(){
        //先拥有锁,才能进入休息室
        lock.lock();
        try {
            while(!hastakeout){
                try {
                    System.out.println("没有饭,歇一会");
                    takeCon.await();

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println("有饭了,干活");
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        MyLock myLock = new MyLock();
        new Thread(() ->{
            myLock.cigratee();
        }).start();

        new Thread(() -> {
            myLock.takeout();
        }).start();

        new Thread(() ->{
            //先拿到锁,才能进入唤醒休息室的线程
            lock.lock();
            try {
                hashcig = true;
                cigCon.signal();
            }finally {
                lock.unlock();
            }


        },"t1").start();
        new Thread(() ->{
            lock.lock();
            try {
                hastakeout = true;
                //唤醒
                takeCon.signal();
            }finally {
                lock.unlock();
            }


        },"t2").start();
    }

}




你可能感兴趣的:(java中condition对象的await和signal方法使用例子)