java线程间通信:生产者--消费者

本文探讨了Java中线程间通信的生产者-消费者问题。讲解了单个生产者消费者如何通过if判断和notify()方法实现,以及在多个生产者消费者场景下,为何需要使用while判断和notifyAll()来确保线程正确同步和唤醒。并展示了程序运行的界面效果。
摘要由CSDN通过智能技术生成

单个生产者消费者问题:定义if判断标记,定义notify();
对于多个生产者消费者问题,则要定义while判断标记,因为为了让被唤醒的线程再一次判断标记;
对于多个生产者消费者问题,要定义notifyAll(),因为需要唤醒对方线程,只用notify()容易出现只唤醒本方线程的情况,导致程序中所有线程都等待。
生产者消费者问题程序如下:

class Resource
{
    private String name;
    private int count=0;
    private boolean flag=false;
    public synchronized void set(String name)
    {
            if(flag)
        //while(flag)
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            this.name=name+"--"+count++;
            System.out.println(Thread.currentThread().getName()+"—--生产者---"+this.name);
            flag=true;
            notify();
            //this.notifyAll();
        }
    public synchronized void out()
    {
        if(!flag)
        //while(!flag)
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"—--消费者---------------"+this.name);
            flag=false;
            notify();
            //this.notifyAll();
    }
}

class Producer implements Runnable
{
    Resource res;
    Producer(Resource res)
    {
        this.res=res;
    }
    @Override
    public synchronized void run() {
        // TODO Auto-generated method stub
        while(true)
        {
            res.set("+商品+");    
        }

    }

}
class Consumer implements Runnable
{
    Resource res;
    Consumer(Resource res)
    {
        this.res=res;
    }   
    @Override
    public synchronized void run() {
        // TODO Auto-generated method stub
        while(true)
        {
            res.out();  
        }

    }

}
public class ProducerConsumerDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Resource res=new Resource();

        Producer pro=new Producer(res);
        Consumer con=new Consumer(res);

        Thread t1=new Thread(pro);
        //Thread t2=new Thread(pro);
        Thread t3=new Thread(con);
        //Thread t4=new Thread(con);

        t1.start();
        //t2.start();
        t3.start();
        //t4.start();

    }

}

单个生产者消费者运行界面如下:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值