diff --git a/datastructure/src/main/java/org/alis/smallcc/algorithm/thread/OrderPrintThread.java b/datastructure/src/main/java/org/alis/smallcc/algorithm/thread/OrderPrintThread.java new file mode 100644 index 0000000..558d9bb --- /dev/null +++ b/datastructure/src/main/java/org/alis/smallcc/algorithm/thread/OrderPrintThread.java @@ -0,0 +1,42 @@ +package org.alis.smallcc.algorithm.thread; + +/** + * 顺序打印奇数 偶数 + * @author alis + */ +public class OrderPrintThread { + + private final Object monitor = new Object(); + private final int limit; + private volatile int count; + + OrderPrintThread(int initCount, int times) { + this.count = initCount; + this.limit = times; + } + + private void print() { + + synchronized (monitor) { + while (count < limit){ + try { + System.out.printf("线程[%s]打印数字:%d%n", Thread.currentThread().getName(), ++count); + monitor.notifyAll(); + monitor.wait(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + //防止有子线程被阻塞未被唤醒,导致主线程不退出 + monitor.notifyAll(); + } + } + + public static void main(String[] args) { + + OrderPrintThread printer = new OrderPrintThread(0, 10); + new Thread(printer::print, "odd").start(); + new Thread(printer::print, "even").start(); + } + +} \ No newline at end of file