C/C++教程

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

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

这篇关于2个线程交替输出A1B2C3问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!