三个线程循环打印ABC

思路
1、定义两个信号量,A的默认个数为1,B的默认值为0,一个用于打印A,一个用于打印B
2、A线程获取到信号量A后打印"A",打印完后释放一个信号量B,让B可以打印
3、B线程获取到信号量B后打印"B",打印完后释放一个信号量A,让A可以打印

public class TestPrint {
    public static void main(String[] args) {
        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(1);
        PrintA printA = new PrintA(semaphoreA,semaphoreB);
        PrintB printB = new PrintB(semaphoreA,semaphoreB);
        try {
            Thread tA = new Thread(printA);
            Thread tB = new Thread(printB);
            tA.start();
            tB.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

class PrintA implements Runnable{
    Semaphore semaphoreA;
    Semaphore semaphoreB;
    public PrintA(Semaphore semaphoreA,Semaphore semaphoreB){
        this.semaphoreA = semaphoreA;
        this.semaphoreB = semaphoreB;
    }
    @Override
    public void run(){
        try {
            for(int i = 0;i<10;i++) {
                semaphoreA.acquire(1);
                System.out.println("A");
                semaphoreB.release(1);
            }

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

class PrintB implements Runnable{
    Semaphore semaphoreA;
    Semaphore semaphoreB;
    public PrintB(Semaphore semaphoreA,Semaphore semaphoreB){
        this.semaphoreA = semaphoreA;
        this.semaphoreB = semaphoreB;
    }
    @Override
    public void run(){
        for(int i = 0;i<10;i++) {
            try {
                semaphoreB.acquire(1);
                System.out.println("B");
                semaphoreA.release(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值