【白板编程】三个线程顺序打印ABC

建立三个线程A、B、C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印。

考察多线程类的实际应用

思路 选择使用ReentrantLock 维护一个公有变量,每次打印的时候使用一个Lock锁住,打印完成之后解锁。
package com.ncst.collections;

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

/**
 * @author i
 * @create 2020/7/11 16:32
 * @Description
 */
public class ThreeThreadPrint {
    private static Lock lock = new ReentrantLock();
    private static int state = 0;//通过state的值来确定是哪个线程打印

    static class ThreadA implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10 ; ) {
                try {
                    lock.lock();
                    while(state%3==0){//多线程并发,不能用if 必须用循环测试等待条件,避免虚假唤醒
                        System.out.print("A->");
                        state++;
                        i++;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }

    static class ThreadB implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10 ; ) {
                try {
                    lock.lock();
                    while(state%3==1){
                        System.out.print("B->");
                        state++;
                        i++;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }

    static class ThreadC implements Runnable {

        @Override
        public void run() {
            for (int i = 0; i < 10 ; ) {
                try {
                    lock.lock();
                    while(state%3==2){
                        System.out.print("C->");
                        state++;
                        i++;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new ThreadA()).start();
        new Thread(new ThreadB()).start();
        new Thread(new ThreadC()).start();
    }

}

你可能感兴趣的:(#,面经)