生产者和消费者问题 ,为什么结果有些不对。麻烦高人帮忙看看
结果为什么不是 放一个 取一个 ?
class Test
{
public static void main(String[] args)
{
Queue q=new Queue();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
class Producer implements Runnable
{
Queue q;
Producer(Queue q)
{
this.q=q;
}
public void run()
{
for(int i=0;i <10;i++)
{
q.put(i);
System.out.println( "Producer put "+i);
}
}
}
class Consumer implements Runnable
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println( "Consumer get "+ q.get());
}
}
}
class Queue
{
boolean isFull=false;
int value;
public synchronized void put(int i)
{
if(isFull)
{
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
value=i;
isFull=true;
notify();
}
public synchronized int get()
{
if(!isFull)
{
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
isFull=false;
notify();
return value;
}
}
------解决方案--------------------多线程的意思 是模拟两个 CPU 同时运算,但具体分配给每个线程多少时间片,这是不得而知的,所以你启动两个线程,一个存数据,一个取数据, 将存取的方法设置为同步。 不表示就一定是先存后取,因为你的存的过程和取的过程 没有做协调控制, 只是在方法上作同步而已。
------解决方案--------------------你要把你实际的运行结果和你所期望的运行结果贴出来
要不怎么知道你到底在想什么呢?
------解决方案--------------------实际运行结果:
Producer put 0
Producer put 1
Consumer get 0
Producer put 2
Consumer get 1
Consumer get 2
Consumer get 3
Producer put 3
Consumer get 4
Producer put 4
期望运行结果:
Producer put 0
Consumer get 0
Producer put 1
Consumer get 1
Producer put 2
Consumer get 2
Producer put 3
Consumer get 3
Producer put 4
Consumer get 4
------解决方案--------------------楼主写的程序有问题,参考这个看看吧
package test;
class Order {
private static int i = 0;
private int count = i++;
public Order() {
if(count == 50) {
System.out.println( "没有食物了! ");
System.exit(0);
}
}
public String toString() { return "第 " + count + "份食物\n "; }
}
class WaitPerson extends Thread {
private Restaurant restaurant;
public WaitPerson(Restaurant r) {
restaurant = r;
start();
}
public void run() {
while(true) {
while(restaurant.order == null)
synchronized(this) {
try {
wait();
} catch(InterruptedException e) {
throw new
RuntimeException(e);
}
}