其他分享
首页 > 其他分享> > 2个线程交替输出A1B2C3问题

2个线程交替输出A1B2C3问题

作者:互联网

引言

经典多线程编程面试题
使用两个线程交替输出A1B2C3......Z26

实现方案1

   public static void method2() throws InterruptedException {

        Object object = new Object();
        AtomicInteger atomicInteger = new AtomicInteger(0);

        new Thread(() -> {
            int i = 0;
            while (i < 26) {
                synchronized (object) {
                    if (atomicInteger.get() % 2 == 0) {
                        atomicInteger.incrementAndGet();
                        System.out.print((char) (i++ + 'A'));
                    } else {
                        Thread.yield();
                    }
                }
            }
        }).start();

        new Thread(() -> {
            int i = 0;
            while (i < 26) {
                synchronized (object) {
                    if (atomicInteger.get() % 2 != 0) {
                        atomicInteger.incrementAndGet();
                        System.out.print(++i);
                    } else {
                        Thread.yield();
                    }
                }
            }
        }).start();
        
    }

实现方案2

存在一定问题,有可能输出 1A2B3C

 public void method1() {
        Object object = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (object) {
                for (int i = 1; i <= 26; i++) {
                    System.out.print(String.valueOf((char) ('A' + i - 1)));
                    object.notify();
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread t2 = new Thread(() -> {
            synchronized (object) {
                for (int i = 1; i <= 26; i++) {
                    System.out.print(i);
                    object.notify();
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t1.start();
        t2.start();
    }

若存在问题,欢迎大家指出

标签:synchronized,Thread,int,object,A1B2C3,交替,线程,atomicInteger,new
来源: https://www.cnblogs.com/yanchuanbin/p/14796995.html