selector

master
robin 3 years ago
parent 667e179af7
commit db64b43399

@ -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();
}
}
Loading…
Cancel
Save