三个线程轮流执行顺序打印ABC

public class ThreadThreadp{
    public static String TAG = "ThreadThreadp";
    private int flag = 0;

    public synchronized void printa() throws InterruptedException{
        while(true){
            if(flag==0){
                Log.d(TAG,"A");
                flag = 1;
                notifyAll();
            }
            wait();
        }
    }

    public synchronized void printb() throws InterruptedException{
        while(true){
            if(flag==1){
                Log.d(TAG,"B");
                flag = 2;
                notifyAll();
            }
            wait();
        }
    }

    public synchronized void printc() throws InterruptedException{
        while(true){
            if(flag==2){
                Log.d(TAG,"C");
                flag = 0;
                notifyAll();
            }
            wait();
        }
    }

    public static void main(){
        ThreadThreadp t = new ThreadThreadp();
        PrintA printA = new PrintA(t);
        PrintB printB = new PrintB(t);
        PrintC printC = new PrintC(t);

        Thread t1 = new Thread(printA);
        Thread t2 = new Thread(printB);
        Thread t3 = new Thread(printC);
        t1.start();
        t2.start();
        t3.start();
    }
}

class PrintA implements Runnable{
    private ThreadThreadp t;
    PrintA(ThreadThreadp t){
        this.t = t;
    }

    @Override
    public void run() {
        try {
            t.printa();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class PrintB implements Runnable{
    private ThreadThreadp t;
    PrintB(ThreadThreadp t){
        this.t = t;
    }

    @Override
    public void run() {
        try {
            t.printb();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class PrintC implements Runnable{
    private ThreadThreadp t;
    PrintC(ThreadThreadp t){
        this.t = t;
    }

    @Override
    public void run() {
        try {
            t.printc();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

参考:

notify() 和 notifyAll() 有什么区别?

notify() 和 notifyAll() 有什么区别?_ConstXiong-CSDN博客_notifyall

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值