三个线程轮流执行顺序打印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();
            }
        }
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用Java中的多线程机制来实现三个线程顺序打印ABC。以下是一种可能的实现方式: ```java public class PrintABC { private static final Object lock = new Object(); // 共享锁对象 private static volatile int state = 0; // 当前打印状态,0表示打印A,1表示打印B,2表示打印C public static void main(String[] args) { Thread threadA = new Thread(new PrintThread("A", 0)); Thread threadB = new Thread(new PrintThread("B", 1)); Thread threadC = new Thread(new PrintThread("C", 2)); threadA.start(); threadB.start(); threadC.start(); } static class PrintThread implements Runnable { private String name; private int targetState; public PrintThread(String name, int targetState) { this.name = name; this.targetState = targetState; } @Override public void run() { for (int i = 0; i < 10; i++) { // 打印10次 synchronized (lock) { while (state != targetState) { // 当前状态不是目标状态,等待 try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(name); // 打印字符 state = (state + 1) % 3; // 更新状态 lock.notifyAll(); // 唤醒其他线程 } } } } } ``` 在上述代码中,我们创建了一个共享的锁对象 `lock` 和一个共享的状态变量 `state`。每个线程在运行时,都会先检查当前的状态是否为目标状态,如果不是则等待,直到状态匹配后打印对应的字符,并更新状态,然后唤醒其他线程。 通过 `Thread.currentThread().getName()` 可以获取当前线程的名字。 以上代码是一种简单的实现方式,但是由于多线程执行是不确定的,所以打印的结果可能会交错。若要确保按照顺序打印ABC,可以使用信号量(Semaphore)等更高级的同步机制。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值