java实现生产者与消费者问题

生产者消费者问题是研究多线程程序时绕不开的问题,它的描述是有一块生产者和消费者共享的有界缓冲区,生产者往缓冲区放入产品,消费者从缓冲区取走产品,这个过程可以无休止的执行,不能因缓冲区满生产者放不进产品而终止,也不能因缓冲区空消费者无产品可取而终止。



public class test {

public static final int BUFFER_SIZE = 10;
public static String[] str = new String[BUFFER_SIZE];  //缓冲区
public static int in = 0;    //指向第一个可生产的位置
public static int out = 0;   //指向第一个可消费的位置

public static void main(String args[])
{


    Role con = new Role();
    Thread consumer, producer;

    consumer = new Thread(con);
    producer = new Thread(con);

    consumer.setName("消费者");
    producer.setName("生产者");

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

}


public static class Role implements Runnable
{

    public Role() {

    }
    public void run() {

        while(true)
        {
            try {
                action();
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }

    public  synchronized void action() throws InterruptedException
    {
        if(Thread.currentThread().getName().equals("消费者"))
        {   
            //注意缓冲区非空的条件
            if(in != out) 
            {   
                System.out.println("消费者消费:" + str[out] + ":" + out);
                str[out] = null;
                out++;
                if(out == BUFFER_SIZE)
                    out = 0;
            }
            else {
                wait();
            }
            Thread.sleep(1000);
        }
        else if(Thread.currentThread().getName().equals("生产者"))
        {   
            //注意缓冲区满的条件
            if(((in+1)%BUFFER_SIZE) != out) 
            {   
                System.out.println("生产者生产:" + "Hello" + ":" + in);
                str[in] = "hello";
                in++;
                if(in == BUFFER_SIZE)
                    in = 0;
            }
            else {
                notify();
            }
        }

    }

  }
  }

你可能感兴趣的:(java,生产者,消费者)