阿里面试题 :顺序打印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(() -> {
            synchronized (lock){
                for (int i = 0; i < Max; i++) {
                    while (index % 3 != 0){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    lock.notifyAll();
                    System.out.print("C");
                    index ++ ;
                }
            }

        });
        ta.start();
        tb.start();
        tc.start();
//        System.out.println("测试" + 1 % 3);
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}

解法2 :ReentrantLock结合Condition通知的实现
具体代码如下

package JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 多线程打印之使用ReetrantLock
 * @author: zhanghailang
 * @date: 2021-5-14 19:30
 */
public class ThreadsPrint2 {
    private static final int Max = 10;
    private static int index = 1;
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread ta = new Thread(() ->{
            lock.lock();
            for (int i = 0; i < Max; i ++){
                while (index % 3 != 1 ){
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print("A");
                index ++;
                condition.signalAll();
            }
            lock.unlock();
        });


        Thread tb = new Thread(() ->{
            lock.lock();
            for (int i = 0; i < Max; i ++){
                while (index % 3 != 2){
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print("B");
                index ++;
                condition.signalAll();
            }
            lock.unlock();
        });


        Thread tc = new Thread(() -> {
            lock.lock();
            for (int  i = 0; i < Max; i ++){
                while (index % 3 != 0){
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print("C ");
                index ++;
                condition.signalAll();
            }
            lock.unlock();
        });


        ta.start();
        tb.start();
        tc.start();

    }
}

解法3:使用许可证解法Semaphore
具体代码如下:

package JUC;


import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: 多线程打印的第三种解法
 * 产生一个疑问CountDownLatch能不能解决这个问题呢?
 * @author: zhanghailang
 * @date: 2021-5-14 20:02
 */
public class ThreadsPrint3 {
    private static final int MAX = 10;
    private static int temp = 1;
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1);
        Thread ta = new Thread(() ->{
            for (int i = 0; i < MAX; i ++){
                while (temp %3 != 1){

                }
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("A");
                semaphore.release();
                temp ++;
            }
        });

        Thread tb = new Thread(() ->{
            for (int i = 0; i < MAX; i ++){
                while (temp %3 != 2){

                }
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("B");
                semaphore.release();
                temp ++;
            }
        });

        Thread tc = new Thread(() ->{
            for (int i = 0; i < MAX; i ++){
                while (temp %3 != 0){

                }
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("C");
                System.out.println();
                semaphore.release();
                temp ++;
            }
        });

        ta.start();
        tb.start();
        tc.start();




        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("另一种的许可证使用解法开始 ====== ");

        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(0);
        Semaphore semaphoreC = new Semaphore(0);

        Thread ta1 = new Thread(() -> {
            for (int i = 0; i < MAX; i++){
                try {
                    semaphoreA.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("A");
                semaphoreB.release();
            }
        });

        Thread tb1 = new Thread(() -> {
            for (int i = 0; i < MAX; i++){
                try {
                    semaphoreB.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("B");
                semaphoreC.release();
            }
        });

        Thread tc1 = new Thread(() -> {
            for (int i = 0; i < MAX; i ++){
                try {
                    semaphoreC.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print("C");
                semaphoreA.release();
            }
        });

        ta1.start();
        tb1.start();
        tc1.start();
    }
}

实例代码已提交至Github仓库
有兄弟觉得有问题的话,可以在评论滴滴我
地址:https://github.com/zhanghailang123/DailyZ/tree/master
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值