下班途中刷新闻时看到一道面试题:用程序实现两个线程交替打印 0~100 的奇偶数。
看到“多线程交替”字样,瞬间就想到了SynchronousQueue
。闲言少叙,直接上代码:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
public class CrossPrint {
private static final int MAX = 100;
public static void main(String[] args) {
BlockingQueue<Integer> queue = new SynchronousQueue<>();
new Thread(new PrintTask("Odd ", queue, true)).start();
new Thread(new PrintTask("Even", queue, false)).start();
}
private static class PrintTask implements Runnable {
private String name;
private BlockingQueue<Integer> queue;
private boolean start;
private int value = -1;
public PrintTask(String name, BlockingQueue<Integer> queue, boolean start) {
this.name = name;
this.queue = queue;
this.start = start;
}
@Override
public void run() {
while (value < MAX) {
try {
if (start) {
putValue();
takeValue();
} else {
takeValue();
putValue();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void putValue() throws InterruptedException {
queue.put(++value);
}
private void takeValue() throws InterruptedException {
value = queue.take();
Optional.of(value).filter(it -> it <= MAX)
.ifPresent(it -> System.out.println(name + ":" + it));
}
}
}