四个线程分别交替打印A,B,C,D,再根据输入次数循环打印ABCD

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int count = Integer.parseInt(br.readLine());
    StringBuilder totalSB = new StringBuilder();
    Runner runner = new Runner(totalSB, count);
    new Thread(runner, "A").start();
    new Thread(runner, "B").start();
    new Thread(runner, "C").start();
    new Thread(runner, "D").start();
    // 阻塞直到计数器减为0
    while (Runner.count != 0) {}
    System.out.println(totalSB.toString());
}

static class Runner implements Runnable {
    /**
     * 对象锁
     */
    private Object lock = new Object();
    /**
     * 最终显示结果
     */
    private StringBuilder totalSB;
    /**
     * 全线程可见的索引位置
     */
    private volatile int index = 0;
    /**
     * 单词表
     */
    private final String[] words = {"A","B","C","D"};
    /**
     * 全线程可见的计数器
     */
    public static volatile int count;

    public Runner(StringBuilder totalSB, int count) {
        this.totalSB = totalSB;
        this.count = count;
    }

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        synchronized (lock) {
            while (count > 0) {
                if (words[index].equals(threadName)) {
                    totalSB.append(threadName);
                    if (index == 3) {
                        index = 0;
                    } else {
                        index++;
                    }
                    if ("D".equals(threadName)) {
                        count--;
                    }
                }
                try {
                    lock.wait(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.notifyAll();
            }
        }
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值