Condition实现精确唤醒通知顺序访问

package demo1;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 * 题目:多线程之间按顺序调用,实现 A->B->C
 * 三个线程启动,要求如下:
 * AA 打印5次,BB 打印10次。CC打印15次,依次循环
 *
 * 重点:标志位
 */
public class Test01 {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<=10;i++){
                    data.printA();
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<=10;i++){
                    data.printB();
                }
            }
        },"B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=0;i<=10;i++){
                    data.printC();
                }
            }
        },"C").start();
    }
}
class Data{
    //建一个锁
    private Lock lock = new ReentrantLock();
    //同步监视器,可以一个监视器只监视一个
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    private int number=1;
    public  void printA()  {
        lock.lock();
        try {
            //业务,判断>执行>通知
            while (number!=1){
                //等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"线程输出A");
            number=2;
            //想让2执行,唤醒2
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void printB() {
             lock.lock();
            try {
                while (number!=2){
                    condition2.await();
                }
                System.out.println(Thread.currentThread().getName()+"线程输出B");
                number=3;
                condition3.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
    }

    public void printC(){
        lock.lock();
        try {
            while (number!=3){
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"线程输出C");
            number=1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}




Condition实现精确唤醒通知顺序访问

上一篇:浅谈.Net和Java互相调用的三种方式


下一篇:Mysql数据管理(DML语言)