java - 消费者生产者程序

标签 java

我需要做一个消费者生产者问题作为家庭作业。我被困在重复线程中。仅生产 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();



}

}

最佳答案

使用将由生产者消费者线程共享的BlockingQueue。如果您需要更多帮助,请告诉我。

关于java - 消费者生产者程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19684732/

相关文章:

java - 如何从非主类将变量返回到主类

java - 保存整数的共享首选项

java - 用于 Java 或替代二进制差异格式的 VCDIFF

java - 用 3 个按钮绘制自己的框架

java - Java中使用wait()和notify()的生产者消费者程序

java - JAX-RS ExceptionMapper 异常拆分

java - 如何使用 JDBCTemplate.queryForMap 获取 map 数据

java - 使用java获取位于ftp服务器的文件的完整路径

java - Spring和Ehache : Cachemanger

java - Cassandra Java 连接问题