实现3个线程之间依次执行

比如有3个线程A,B,C ,需要按照顺序执行,ABC,ABC 依次执行。

这个使用可以使用 Lock 的 conditional来实现线程之间精准通讯。

点击查看代码
package com.study.juc;

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

/**
 * 功能: TODO
 *
 * @author ASUS
 * @date 2023/11/25 22:40
 */
public class ConditionalDemo {

    public static void main(String[] args) {
        Data data=new Data();
        new Thread(()->{
            for(int i=0;i<10;i++){
                data.printA();
            }

        },"A").start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                data.printB();
            }
        },"B").start();
        new Thread(()->{
            for(int i=0;i<10;i++){
                data.printC();
            }
        },"C").start();
    }


}

class Data{
    private Lock lock=new ReentrantLock();
    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();
    private Condition condition3=lock.newCondition();

    private int number=1;

    public void printA(){
        lock.lock();
        try {
            while (number!=1){
                condition1.await();
            }
            //业务代码
            System.err.println(Thread.currentThread().getName()+"->AAA");
            number=2;

            condition2.signal();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {
            while (number!=2){
                condition2.await();
            }
            System.err.println(Thread.currentThread().getName()+"->BBB");
            number=3;

            condition3.signal();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {
            while (number!=3){
                condition3.await();
            }
            System.err.println(Thread.currentThread().getName()+"->CCC");
            number=1;

            condition1.signal();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }

}

posted on 2023-11-25 22:58  自由港  阅读(13)  评论(0编辑  收藏  举报