這幾天一直在看多線程。其中最多見的就是 生產者消費者 的問題。代碼以下:java
//一個定長的隊列 Queue<Integer> queue = new LinkedList<Integer>();
public void run() { while(true) { //(1) synchronized(queue) { while(queue.size() == maxSize) { try { System.out.println("Queue is full, Producer thread waiting for, consumer to take something from queue"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int i = new Random().nextInt(); queue.add(i); System.out.println("Producing value : " + i); //(2) queue.notifyAll(); } } }
@Override public void run() { while(true) { synchronized(queue) { while(queue.isEmpty()) { System.out.println("Queue is empty, Consumer thread is waiting, for producer thread to put something in queue"); try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //消費 System.out.println(Thread.currentThread().getName() + "value : " + queue.remove()); queue.notifyAll(); } } }
生產者
仍是消費者
?