生产者和消费者成功解答synchroniz…

本文介绍了一个使用Java实现的生产者消费者模式案例。该模式通过一个共享仓库类协调生产者线程与消费者线程间的同步问题,确保数据生产和消费的正确性。文章详细展示了如何利用synchronized关键字和wait/notify机制来实现线程间的数据交换。

class Storage {//仓库类,用于生产产品和消费产品
  int n;
  boolean valueSet = false;

  synchronized int get() { //消费产品
    while(!valueSet)
      try {
        wait(); //消费者消耗了产品后需要wait,来等待生产者生产产品

      } catch(InterruptedException e) {
     
        System.out.println("InterruptedException caught");
      }
    try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      System.out.println("Got: " + n);
      valueSet = false;
      notify(); //当产品消费了之后,需要唤醒被wait的put()来生产产品
      return n;
  }

  synchronized void put(int n) { //生产产品
    while(valueSet)
      try {
        wait(); //当valueSet为true时,停止生产产品
      } catch(InterruptedException e) {
        System.out.println("InterruptedException caught");
      }

      this.n = n;
      valueSet = true;
      try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      System.out.println("Put: " + n);
      notify(); //put()生产了产品后需要唤醒消费者去get()消耗产品
  }
}

class Producer implements Runnable {
Storage q;

  Producer(Storage q) {
    this.q = q;
    new Thread(this, "Producer").start();
  }

  public void run() {
    int i = 0;

    while(true) {
      q.put(i++);
    }
  }
}

class Consumer implements Runnable {
Storage q;

  Consumer(Storage q) {
    this.q = q;
    new Thread(this, "Consumer").start();
  }

  public void run() {
    while(true) {
      q.get();
    }
  }
}

class consumer_producer {
  public static void main(String args[]) {
  Storage q = new Storage();
    new Producer(q);
    new Consumer(q);

    System.out.println("Press Control-C to stop.");
  }
}


生产者和消费者成功解答synchronized <wbr>的疑惑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值