龙空技术网

java实现多线程交替打印字符

Admin123 77

前言:

今天我们对“java多线程顺序打印”可能比较注重,朋友们都想要知道一些“java多线程顺序打印”的相关内容。那么小编同时在网摘上搜集了一些对于“java多线程顺序打印””的相关文章,希望姐妹们能喜欢,我们一起来了解一下吧!

首先定义打印字符的类,

@Data@AllArgsConstructorclass PrintNumber {    private int flag;    private int loopNumber;    /**     * 重点在于current和next 无论用ReentrantLock还是LockSupport来实现都是这样做.     *     * @param printedChar     * @param flag     * @param nextFlag     */    void printNumber(String printedChar, int flag, int nextFlag) {        synchronized (this) {            int printCount = 0;            while (printCount < this.loopNumber) {                while (flag != this.flag) {                    try {                        this.wait();                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }                System.out.print(printedChar);                this.flag = nextFlag;                printCount++;                this.notifyAll();            }        }    }}

测试类,

public static void main(String[] args) {    Map<Integer, String> flex = new HashMap<>(3);    flex.put(1, "a");    flex.put(2, "b");    flex.put(3, "c");    PrintNumber printNumber = new PrintNumber(1, 5);    for (int i = 1; i < 4; i++) {        int finalI = i;        new Thread(() -> {            if (finalI == 3) {                printNumber.printNumber(flex.get(finalI), finalI, 1);            } else {                printNumber.printNumber(flex.get(finalI), finalI, finalI + 1);            }        }, "t" + i).start();    }}

标签: #java多线程顺序打印