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();
    }

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

上一篇:7.java中的13个原子操作类


下一篇:程序员深夜惨遭老婆鄙视,原因竟是CAS原理太简单?| 每一张图都力求精美