面试题--有三个线程ID分别是A、B、C,请用多线编程实现,在屏幕上循环打印10次ABCABC

有三个线程ID分别是A、B、C,请用多线编程实现,在屏幕上循环打印10次ABCABC

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: july
 * @date: 2020/3/22 10:12
 * @description:
 */
public class Test01 {

    public static void main(String[] args) {
        MajusculeABC maj = new MajusculeABC();
        Thread t_a = new Thread(new Thread_ABC(maj, 'A'));
        Thread t_b = new Thread(new Thread_ABC(maj, 'B'));
        Thread t_c = new Thread(new Thread_ABC(maj, 'C'));
        t_a.start();
        t_b.start();
        t_c.start();
        System.out.println();
    }

    static class MajusculeABC {
        LinkedList list = new LinkedList();
        int idx = 0;
        int loopCountMax = 10;
        int currentLoop = 0;

        public Character currentChar() {
            int i = idx % list.size();
            int c = idx / list.size();
            if (i == 0 && idx != 0) {
                currentLoop += c;
                idx = 0;
                if (currentLoop >= loopCountMax) {
                    currentLoop = -1;
                    System.out.println();
                    return null;
                }
                System.out.println();
            }
            return list.get(i);
        }

        public void add(Character character) {
            list.add(character);
        }
    }

    static class Thread_ABC implements Runnable {
        MajusculeABC maj;
        Character c;

        public Thread_ABC(MajusculeABC maj, char c) {
            maj.add(c);
            this.maj = maj;
            this.c = c;
        }

        @Override
        public void run() {

            while (true) {
                synchronized (maj) {

                    if (maj.currentLoop < 0) {
                        maj.notifyAll();
                        break;
                    } else {
                        if (Objects.equals(maj.currentChar(), this.c)) {
                            System.out.print(c);
                            maj.idx++;
                        }
                        try {
                            maj.notifyAll();
                            maj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

}

你可能感兴趣的:(java)