2、线程间定制化调用通信--使用Lock锁机制

1、多线程编程

  • 线程操作资源类
  • 高内聚 低耦合
  • 资源类中
    • 判断
    • 干活
    • 通知
  • 注意多线程之间的虚假唤醒

2、步骤

  • 有顺序通知,需要标识位
  • 有一个锁Lock,有3把钥匙Condition
  • 判断标志位
  • 输出线程名+第几次+第几轮
  • 修改标志位,通知下一个
class ShareResource{
    private int number = 1;//1:A  2:B 3:c
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print5(int totalLoopNumber){
        lock.lock();
        try {
            //1、判断
            while (number != 1){
                //A 停止
                c1.await();
            }
            for (int i = 0; i < 5 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t totalLoopNumber: "+totalLoopNumber);
            }
            //3、通知
            number = 2;
            c2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print10(int totalLoopNumber){
        lock.lock();
        try {
            //1、判断
            while (number != 2){
                //B 停止
                c2.await();
            }
            for (int i = 0; i < 10 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t totalLoopNumber: "+totalLoopNumber);
            }
            //3、通知
            number = 3;
            c3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void print15(int totalLoopNumber){
        lock.lock();
        try {
            //1、判断
            while (number != 3){
                //A 停止
                c3.await();
            }
            for (int i = 0; i < 15 ; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t totalLoopNumber: "+totalLoopNumber);
            }
            //3、通知
            number = 1;
            c1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

/**
 *
 * @Description:
 * 多线程之间按顺序调用,实现A->B->C
 * 三个线程启动,要求如下:
 *
 * AA打印5次,BB打印10次,CC打印15次
 * 接着
 * AA打印5次,BB打印10次,CC打印15次
 * ......来5轮
 *
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(()->{
            for (int i = 0; i < 5 ; i++) {
                shareResource.print5(i);
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 5 ; i++) {
                shareResource.print10(i);
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i < 5 ; i++) {
                shareResource.print15(i);
            }
        },"CC").start();
    }

}

你可能感兴趣的:(2、线程间定制化调用通信--使用Lock锁机制)