這是生產者消費者模式的作業實現。下面的實現有什麼問題。我已經搜索了各種實現,但我無法理解我的錯誤。在Java中實現生產者消費者
我有一個共享隊列
我同步於相同的鎖
實施
共享隊列生產者和消費者:
class SharedQueue{
public static Queue<Integer> queue = new LinkedList<Integer>();
}
生產者線程:
//The producer thread
class Producer implements Runnable{
public void run()
{
synchronized (SharedQueue.queue)
{
if(SharedQueue.queue.size() >=5)
{
try {
SharedQueue.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Random r = new Random();
int x = r.nextInt(10);
System.out.println("Inside Producer" + x);
SharedQueue.queue.offer(x);
SharedQueue.queue.notify();
}
}
}
消費主題:
class Consumer implements Runnable{
public void run()
{
synchronized (SharedQueue.queue)
{
if(SharedQueue.queue.size() == 0)
{
try {
SharedQueue.queue.wait();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
int k = SharedQueue.queue.remove();
System.out.println("Inside consumer" + k);
}
}
}
主程序
public class ProducerConsumerTest {
public static void main(String[] args)
{
Thread p = new Thread(new Producer());
Thread q = new Thread(new Consumer());
p.start();
q.start();
}
}
我不知道。哪裏不對?什麼地方出了錯? [Stack Overflow不是心靈讀者或水晶球。](http://meta.stackexchange.com/a/128551/133242) – 2012-04-23 02:46:51
作爲一般規則,更喜歡'java.util.concurrent'中的實用程序來使用代碼等待和通知。(Effective Java,item 69) – 2012-04-23 02:53:11