1

我需要为家庭作业制作一个消费者生产者问题。我被困在重复线程。仅生产 1 个对象,仅消耗 1 个对象。如果对象存在于数组中,则生产者不会生产并等待消费者消费它。

class PC extends Thread{
static int i=1;
static int storage[]=new int[1];
String info;

PC(String _info)
{
    this.info=_info;
}

public synchronized void consume()
{
    if(storage[0]==-1) 
    {   
        try { 
            System.out.println("C: 0" ); 
        wait(); 
        } catch(InterruptedException e) { 
        System.out.println("InterruptedException caught"); 
        } 
    }

    else
        {
        System.out.println("C: " + storage[0]); 
        storage[0]=-1;
        i++;

        notify(); 
        }       
}

public synchronized void prod()
{
    if(storage[0]!=-1) 
    {   
        try { 
            System.out.println("P: 0" );
        wait(); 

        } catch(InterruptedException e) { 
        System.out.println("InterruptedException caught"); 
        } 
    }
    else
        {
        storage[0]=i;

        System.out.println("P: " + storage[0]); 

        notify(); 
        }   
}

public void run()
{
    if(info=="producer"){

        prod();
    }
    else
        consume();
}


public static void main(String args[])
{

    storage[0]=-1;


    PC consumer =new PC("consumer");
    PC producer =new PC("producer");

    consumer.start();
    producer.start();



}

}

4

3 回答 3

0

使用BlockingQueue将由producerconsumer线程共享。如果您需要更多帮助,请告诉我。

于 2013-10-30T14:16:13.877 回答
0

仅生产 1 个对象,仅消耗 1 个对象。

嗯,是的:

public void run()
{
    if(info=="producer"){

        prod();
    }
    else
        consume();
}

(您还可以在不同的对象上同步,因此线程不会共享监视器。这意味着类变量“存储”也不受保护。)

于 2013-10-30T14:52:41.190 回答
0

You'll need to have a loop in your run() method. Either a while-loop, or if you want to produce/consume a certain amount of items, you can use a for-loop.

Pay attention to the String comparison too.

于 2013-10-30T14:27:32.600 回答