From db64b43399aa8f3fd2a20f7c349ea8babc197d01 Mon Sep 17 00:00:00 2001 From: robin Date: Mon, 11 Apr 2022 19:00:51 +0800 Subject: [PATCH] :sparkles: selector --- .../algorithm/thread/OrderPrintThread.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 datastructure/src/main/java/org/alis/smallcc/algorithm/thread/OrderPrintThread.java 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