实现思路是使用锁来控制不同线程的执行。下面有两种实现:
1、使用对象监视器:
public class OddEvenPrinter {
private final Object monitor = new Object();
private final int limit;
private volatile int count;
public OddEvenPrinter(int limit, int initCount) {
this.limit = limit;
this.count = initCount;
}
public void print() {
synchronized (monitor) {
while (count < limit) {
try {
System.out.println(String.format("线程[%s]打印数字:%d", Thread.currentThread().getName(), ++count));
monitor.notifyAll();
monitor.wait();
} catch (InterruptedException e) {
//ignore
}
}
}
}
public static void main(String[] args) throws Exception {
OddEvenPrinter printer = new OddEvenPrinter(10, 0);
Thread thread1 = new Thread(printer::print, "thread-1");
Thread thread2 = new Thread(printer::print, "thread-2");
thread1.start();
thread2.start();
Thread.sleep(Integer.MAX_VALUE);
}
}
2、使用jdk的并发库:
public class OddEvenPrinterEx {
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private final int limit;
private volatile int count;
public OddEvenPrinterEx(int limit, int initCount) {
this.limit = limit;
this.count = initCount;
}
public void print() {
lock.lock();
try {
while (count < limit){
System.out.println(String.format("线程[%s]打印数字:%d", Thread.currentThread().getName(), ++count));
condition.signalAll();
try {
condition.await();
} catch (InterruptedException e) {
//ignore
}
}
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws Exception {
OddEvenPrinterEx printer = new OddEvenPrinterEx(10, 0);
Thread thread1 = new Thread(printer::print, "thread-1");
Thread thread2 = new Thread(printer::print, "thread-2");
thread1.start();
thread2.start();
Thread.sleep(Integer.MAX_VALUE);
}
}