生产和消费

package com.lesson20;

 

//消费者和生产者的关系

public class PrivderConsumer {

 

 /**
  * @param args
  */


 // 多线程的输出


 public static void main(String[] args) {


  // TODO Auto-generated method stub


  // 公共的存储空间


  PeopleData peopledata = new PeopleData();


  Consumer consumer = new Consumer(peopledata);

  Product product = new Product(peopledata);


  // 线程的开始


  Thread t = new Thread(consumer);


  Thread c = new Thread(product);


  t.start();


  c.start();


 }


}


// 只定义个类初始化个变量


class PeopleData {


 String name = "0";


 String sex = "1";


 boolean bfull = false;


}


// 只输出---消费者


class Consumer implements Runnable {


 // 构造函数


 public Consumer(PeopleData peopledata) {


  super();


  this.peopledata = peopledata;

 }


 // 生明PeopleData的引用 变量peopledata


 PeopleData peopledata;


 public void run() {


  while (true) {


   synchronized (peopledata) {


    if (peopledata.bfull == false) {


     try {


      peopledata.wait();


     } catch (Exception e) {


      // TODO: handle exception


     }


    }


    System.out.print(peopledata.name);


    try {


     Thread.sleep(10);


    } catch (Exception e) {


     // TODO: handle exception


    }


    System.out.println(":" + peopledata.sex);


    peopledata.bfull = false;


    peopledata.notify();


   }


  }


 }


}

 

// 制造---生产者


class Product implements Runnable {


 PeopleData peopledata;


 int make = 0;

 

 public void run() {


  while (true) {

 

   // 判断他的线程执行条件


   synchronized (peopledata) {


    if (peopledata.bfull == true) {

 

     try {


      peopledata.wait();


     } catch (Exception e) {


      // TODO: handle exception


     }


    }


    if (make == 0) {


     peopledata.name = "张三";


     try {


      Thread.sleep(10);


     } catch (Exception e) {


      // TODO: handle exception


     }


     peopledata.sex = "男";


    } else {

 

     peopledata.name = "翠花";


     try {


      Thread.sleep(10);


     } catch (Exception e) {


      // TODO: handle exception


     }


     peopledata.sex = "女";


    }


    make = (make + 1) % 2;


    peopledata.bfull = true;


    peopledata.notify();

 

   }


  }


 }

 

 // 构造函数

 

 public Product(PeopleData peopledata) {


  super();


  this.peopledata = peopledata;


 }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值