public class TestA extends TestBase { // 生產者 static class Producer implements Runnable { private final TransferQueue<String> queue; public Producer(TransferQueue<String> queue) { this.queue = queue; } private String produce() { return "Your lucky number " + (new Random().nextInt(100)); } @Override public void run() { // TODO Auto-generated method stub try { while (true) { if (queue.hasWaitingConsumer()) { String ss = produce(); System.out.println("生產一條數據 produce="+ss); queue.transfer(ss); } TimeUnit.SECONDS.sleep(1); } } catch (InterruptedException e){ } } } static class Consumer implements Runnable{ private final TransferQueue<String> queue; public Consumer(TransferQueue<String> queue) { this.queue = queue; } @Override public void run() { // TODO Auto-generated method stub try { System.out.println("Consumer " + Thread.currentThread().getName() + queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } } static class ThreadMain { public static void main(String[] args) { TransferQueue<String> queue = new LinkedTransferQueue<String>(); Thread producer = new Thread(new Producer(queue)); producer.setDaemon(true); producer.start();// 開始生產 for (int i = 0; i < 10; i++) { Thread consumer = new Thread(new Consumer(queue)); consumer.setDaemon(true); consumer.start();// 開始消費 try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } } }