如果你想尝试平衡一切,你应该创建一个队列来保存要打印的数字,然后让一个线程生成它们(生产者),另一个线程读取并打印它们(消费者)。这可以通过LinkedBlockingQueue轻松完成。
public class PrintQueueExample {
private BlockingQueue printQueue = new LinkedBlockingQueue();
public static void main(String[] args) throws InterruptedException {
PrinterThread thread = new PrinterThread();
thread.start();
for (int i = 0; i < 1000000; i++) {
int toPrint = ...(i) ;
printQueue.put(Integer.valueOf(toPrint));
}
thread.interrupt();
thread.join();
System.out.println("Complete");
}
private static class PrinterThread extends Thread {
@Override
public void run() {
try {
while (true) {
Integer toPrint = printQueue.take();
System.out.println(toPrint);
}
} catch (InterruptedException e) {
// Interruption comes from main, means processing numbers has stopped
// Finish remaining numbers and stop thread
List remainingNumbers = new ArrayList();
printQueue.drainTo(remainingNumbers);
for (Integer toPrint : remainingNumbers)
System.out.println(toPrint);
}
}
}
}
此代码可能存在一些问题,但这是它的要点。