⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 producterandcustomer.java

📁 关于一个java线程的问题说明,是以生产者与消费者讲述
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -