JAVA经典生产者、消费者多线程同步例程

package Chenqi;

import java.io.InterruptedIOException;

/**
 *1、制作出基本的生产者、消费者多线程模式
 *2、在1的基础上,增加同步
 *3、在2的基础上优化同步
 */

public class ThreadTest {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Productable p=new Product();
  Producer put=new Producer(p);
  Consumer get=new Consumer(p);
 }
}
//定义产品接口
interface Productable{
 void get();
 void put(int productID);
 boolean isHasProduct();
 void reset();
}
//定义产品类
class Product implements Productable{
 int productID=0;
 private volatile boolean hasProduct=false;
 public boolean isHasProduct() {
  return this.hasProduct;
 }
 public void reset() {
  this.productID=0;
 }
 synchronized public void get() {
  if(!this.isHasProduct()){
   try {
    wait();
   } catch (InterruptedException e) {
    System.out.println("get process interrupted!");
   }
  }  
  System.out.println("get : "+this.productID);
  this.hasProduct=false;
  this.reset();
  notify();
 }
 synchronized public void put(int productID) {
  if(this.isHasProduct()){
   try {
    wait();
   } catch (InterruptedException e) {
    System.out.println("put process interrupted!");
   }
  }
  this.productID=productID;
  System.out.println("put : "+this.productID);
  this.hasProduct=true;
  notify();
 }
}
//定义生产者线程
class Producer implements Runnable{
 Productable p;
 public Producer(Productable p) {
  this.p=p;
  new Thread(this,"Producer").start();
 }
 public void run() {
  int i=2;
  while(true){
   p.put(++i);
  }
 }
}
//定义消费者类
class Consumer implements Runnable{
 Productable p;
 public Consumer(Productable p) {
  this.p=p;
  new Thread(this,"Consumer").start();
 }
 public void run() {
  while(true){
   p.get();
  }
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值