producterandcustomer.java

来自「关于一个java线程的问题说明,是以生产者与消费者讲述」· Java 代码 · 共 94 行

JAVA
94
字号
class Producter extends Thread
{
        CubbyHole cubbyhole;
        int productionID = 1;
        Producter(CubbyHole c)
        {
                cubbyhole = c;
        }
        public void run()
        {
                for(int i = 0; i < 10; i++)
                {
                        cubbyhole.put(productionID);        //生产了一件产品
                        System.out.println("Product " + productionID++);
                        try
                        {
                                sleep(2000);
                        }
                        catch(InterruptedException e)
                        {
                                System.out.println("Error: " + e);
                        }
                }
        }
}

class Customer extends Thread
{
        CubbyHole cubbyhole;
        int productionID;
        Customer(CubbyHole c)
        {
                cubbyhole = c;
        }
        public void run()
        {
                for(int i = 0;i < 10;i++)
                {
                        productionID = cubbyhole.get();
                        System.out.println("Custom  " + productionID);
                }
        }
}

class CubbyHole
{
        int seq;
        boolean availlable = false;        //初始时文件夹无产品,未满
        public synchronized void put(int id)
        {
                while(availlable == true)        //满了
                {
                        try
                        {
                                wait();        //等待
                        }
                        catch(InterruptedException e)
                        {
                                System.out.println("Error: " + e);
                        }
                }
                seq = id;
                availlable = true;        //生产者放入产品,可用了
                notify();
        }
        public synchronized int get()
        {
                while(availlable == false)        //无产品等待
                {
                        try
                        {
                                wait();
                        }
                        catch(InterruptedException e)
                        {
                                System.out.println("Error: " + e);
                        }
                }
                availlable = false;        //消费了产品,文件夹空
                notify();
                return seq;
        }
}
public class ProducterAndCustomer
{
        public static void main(String args[])
        {
                CubbyHole cubbyhole = new CubbyHole();
                Producter p = new Producter(cubbyhole);
                p.start();
                Customer c = new Customer(cubbyhole);
                c.start();
        }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?