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

📄 producerandconsumer2.java

📁 Java面向对象编程(随书配套源代码) 阐述了面向对象编程的思想
💻 JAVA
字号:
package chapter10;
public class ProducerAndConsumer2 
{
    public static void main(String args[]) 
    {
        Quantity q=new Quantity();
        new Producer(q);
        new Consumer(q);
        System.out.println("Press Control-C to stop.");
    }
}
class Quantity 
{
    int n;
    //标志变量,为false表示可以生产数据不允许消费;
    //为true表示表示允许消费而不允许生产
    boolean blnValue=false;
    synchronized int get() 
    {
        if(!blnValue)
           try
           {//如果没有生产数据,则使消费线程处于等待状态
               wait();
           } 
           catch (InterruptedException e) 
           {
               System.out.println("InterruptedException caught");
           }
        //消费数据,同时唤醒生产线程
        System.out.println("Got: "+n);
        blnValue=false;
        notify();
        return n;
    }
    synchronized void put(int n) 
    {
        if(blnValue)
           try
           {//如果没有消费数据,则使生产线程处于等待状态
               wait();
           } catch(InterruptedException e) 
           {
               System.out.println("InterruptedException caught");
           }
        //生产数据,同时唤醒消费线程
        this.n=n;
        blnValue=true;
        System.out.println("Put: "+n);
        notify();
    }
}
class Producer implements Runnable 
{
    Quantity q;
    Producer(Quantity q) 
    {
        this.q=q;
        new Thread(this,"Producer").start();
    }
    public void run() 
    {
        int i=0;
        while(true) 
        {
            q.put(i++);
        }
    }
}
class Consumer implements Runnable 
{
    Quantity q;
    Consumer(Quantity q) 
    {
        this.q=q;
        new Thread(this,"Consumer").start();
    }
    public void run() 
    {
        while(true) 
        {
            q.get();
        }
    }
}

⌨️ 快捷键说明

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