继 生产和消费

来源:互联网 发布:淘宝美工主页设计 编辑:程序博客网 时间:2024/04/27 18:18

package com.zhihualesson20_1;

 

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


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;


//用它两可以说明线程同步


 synchronized void writeData(String name, String sex) {

 

  if (this.bfull == true) {


   try {


    this.wait();


   } catch (Exception e) {


    // TODO: handle exception

 


   }


  }

 

  this.name = name;


  try {


   Thread.sleep(10);


  } catch (Exception e) {

 


   // TODO: handle exception


  }


  this.sex = sex;

 

  this.bfull = true;


  this.notify();


 }

 

 synchronized void getData() {


  if (this.bfull == false) {


   try {


    this.wait();


   } catch (Exception e) {


    // TODO: handle exception


   }


  }


  System.out.print(this.name);


  try {


   Thread.sleep(10);


  } catch (Exception e) {


   // TODO: handle exception


  }


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


  this.bfull = false;


  this.notify();


 }


}

 

// 只输出---消费者


class Consumer implements Runnable {


 // 构造函数


 public Consumer(PeopleData peopledata) {


  super();


  this.peopledata = peopledata;


 }

 

 // 生明PeopleData的引用 变量peopledata


 PeopleData peopledata;

 

 public void run() {


  while (true) {


   peopledata.getData();


  }


 }


}

 

// 制造---生产者


class Product implements Runnable {


 PeopleData peopledata;


 int make = 0;

 

 public void run() {


  while (true) {


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


   synchronized (peopledata) {

 

    if (make == 0) {


     peopledata.writeData("张三", "男");


    } else {


     peopledata.writeData("翠花", "女");

 

    }


    make = (make + 1) % 2;

 

   }


  }


 }

 

 // 构造函数


 public Product(PeopleData peopledata) {


  super();


  this.peopledata = peopledata;


 }


}

原创粉丝点击