多线程 交替打印,控制线程执行顺序 ReentrantLock 使用

主要 就是3步走
  1. 条件判断
  2. 执行任务
  3. 设置信号变量,唤醒对应的线程
package test;

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

/**
 * @author lyc
 * @date 2021/2/20
 */
public class TestThread {

    private static int j = 0;
    static Lock lock = new ReentrantLock();
    static Condition conditionA = lock.newCondition();
    static Condition conditionB = lock.newCondition();
    static Condition conditionC = lock.newCondition();


    public void printA() throws InterruptedException {
        lock.lock();
        while (j!=0){
            conditionA.await();
        }
        System.out.print(Thread.currentThread().getName()+"A");
        j++;
        conditionB.signal();
        lock.unlock();
    }

    public void printB() throws InterruptedException {
        lock.lock();
        while (j!=1){
            conditionB.await();
        }
        System.out.print(Thread.currentThread().getName()+"B");
        j++;
        conditionC.signal();
        lock.unlock();
    }

    public void printC() throws InterruptedException {
        lock.lock();
        while (j!=2){
            conditionC.await();
        }
        System.out.println(Thread.currentThread().getName()+"C");
        j = 0;
        conditionA.signal();
        lock.unlock();
    }

    public static void main(String[] args) throws InterruptedException {
        TestThread testThread = new TestThread();
        new Thread(()->{
            try {
                for (int i = 0; i < 5; i++) {
                    testThread.printA();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(()->{
            try {
                for (int i = 0; i < 5; i++) {
                    testThread.printB();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();


        new Thread(()->{
            try {
                for (int i = 0; i < 5; i++) {
                    testThread.printC();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}

posted @ 2021-02-26 17:11  川流不息&  阅读(282)  评论(0编辑  收藏  举报