三个线程轮流执行顺序打印ABC(一):使用Semaphore实现

需求:有三个线程轮流执行,第一个线程打印A,第二个线程打印B,第三个线程打印C……循环10次。

思路:三个线程对应三个Semaphore,三个Semaphore维护一个Permit。当前线程通过对应的Semaphore获取Permit,执行打印,并通过下一个线程对应的Semaphore释放Permit。类似于Permit在当前的线程对应的Semaphore中,传递到了下一个线程对应的Semaphore中。下一个线程通过对应的Semaphore获取Permit,继续执行……循环10次。

效率:每个线程使用一个Semaphore,一个Permit在不同的Semaphore之间循环传递,当前线程消费完Permit后,无法立即进行下一次打印,而下一个线程使用的Semaphore刚好获取到了Permit,从而使线程可以交替执行。不需要额外的线程轮流状态state字段。代码简洁,效率高。

实现代码

package edu.self.multithread;

import java.util.concurrent.Semaphore;

/**
 * Created by SunYanhui on 2017/12/4.
 */
public class MultipleThreadRotationUsingSemaphore {
    public static void main(String[] args) {
        PrintABCUsingSemaphore printABC = new PrintABCUsingSemaphore();
        new Thread(() -> printABC.printA()).start();
        new Thread(() -> printABC.printB()).start();
        new Thread(() -> printABC.printC()).start();
    }
}

class PrintABCUsingSemaphore {
    private Semaphore semaphoreA = new Semaphore(1);
    private Semaphore semaphoreB = new Semaphore(0);
    private Semaphore semaphoreC = new Semaphore(0);
    //private int attempts = 0;


    public void printA() {
        print("A", semaphoreA, semaphoreB);
    }

    public void printB() {
        print("B", semaphoreB, semaphoreC);
    }

    public void printC() {
        print("C", semaphoreC, semaphoreA);
    }

    private void print(String name, Semaphore currentSemaphore, Semaphore nextSemaphore) {
        for (int i = 0; i < 10; ) {
            try {
                currentSemaphore.acquire();
                //System.out.println(Thread.currentThread().getName()+" try to print "+name+", attempts : "+(++attempts));
                System.out.println(Thread.currentThread().getName() +" print "+ name);
                i++;
                nextSemaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值