前言:
今天我们对“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多线程顺序打印