Interview questions: multi-threaded output in order

I recently encountered a problem: write a program and start 3 threads. The IDs of these three threads are A, B, and C. Each thread prints its ID on the screen 10 times, and the output results must be in order display. Such as: ABCABCABC...

At that time, I was very confused and didn't know how to solve it. It seems that I still don't have a deep understanding of threads and locks.

public class MultiLockDemo {
    
    
    /**
     * 使用公平锁,防止一个线程连续获取锁的情况
     */
    private Lock lock = new ReentrantLock(true);
    // 计数
    private int COUNT = 0;
    // 循环次数
    private int LOOP_NUM = 10;
    // 计数取模
    private int MOD = 3;

    private void printChar(int threadIdentify) {
    
    
        for (int i = 0; i < LOOP_NUM; ) {
    
    
            lock.lock();
            try {
    
    
                /**
                 * threadIdentify: 0 表示线程 a, 1 表示线程 b, 2 表示线程 c
                 */
                if (COUNT % MOD == threadIdentify) {
    
    
                    System.out.print(Thread.currentThread().getName());
                    COUNT++;
                    i++;
                }
            } finally {
    
    
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
    
    
        MultiLockDemo lockDemo = new MultiLockDemo();
        Thread a = new Thread(() -> lockDemo.printChar(0), "A");
        Thread b = new Thread(() -> lockDemo.printChar(1), "B");
        Thread c = new Thread(() -> lockDemo.printChar(2), "C");

        a.start();
        b.start();
        c.start();
    }
}

Reference: java multi-threaded sequential execution and sequential output of ABC questions An
interview question: multiple threads output in sequence

Guess you like

Origin blog.csdn.net/jiaobuchong/article/details/86555208