阿里面试题 :顺序打印ABC问题的几种解法

题目描述

编写一个程序,开启三个线程A,B,C , 这三个线程输出分别为 A、B、C,要求,按顺序输出ABC,循环10次, 分别为 ABCABCABCABCABC…

解法1 :用synchronized、wait、notifyAll实现
具体代码如下

package JUC;

/**
 * @description: 多线程打印问题
 * A、B、C
 * @author: zhanghailang
 * @date: 2021-5-13 19:02
 */
public class ThreadsPrint {
   
    private static final int Max = 10;
    private static int index = 1;

    public static void main(String[] args) {
   
        Object lock = new Object();
//        new Thread(()->{
   
//            System.out.println("aaa");
//        }).start();
//
//        new Thread(new Runnable() {
   
//            @Override
//            public void run() {
   
//                System.out.println("zzzz");
//            }
//        }).start();
//
//        Thread a = new Thread(() ->{
   
//            System.out.println("ttttt");
//        });
//        a.start();
//        System.out.println(a.getName());

        /**
         * 此问题引发的思考
         * 1.多线程的交替执行 通信
         * 2.锁的使用
         * 3.wait阻塞和唤醒锁
         * 4.取余数问题
         */

        Thread ta = new Thread(() -> {
   
            synchronized (lock) {
   
                for (int i = 0; i < Max; i++) {
   
                    while (index % 3 != 1) {
   
                        try {
   
                            lock.wait();
                        } catch (InterruptedException e) {
   
                            e.printStackTrace();
                        }
                    }
                    index ++;
                    lock.notifyAll();
                    System.out.print("A");
                }
            }
        });

        Thread tb = new Thread(() -> {
   
            synchronized (lock){
   
                for (int i = 0; i < Max; i++) {
   
                    while (index % 3 != 2){
   
                        try {
   
                            lock.wait();
                        } catch (InterruptedException e) {
   
                            e.printStackTrace();
                        }
                    }
                    lock.notifyAll();
                    System.out.print("B");
                    index ++;
                }
            }
        });

        Thread tc = new Thread(() -> {
   
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值