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