龙空技术网

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

Admin123 103

前言:

目前大家对“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设置打印