| 本帖最后由 左耳的鱼 于 2013-7-21 17:54 编辑 
 package cn.itcast.threaddemo;
 //定义产品类,有品名,生产个数
 class Product {
 private String name ;
 //统计次数变量
 private int count = 1;//这里为什么重1开始????????????
 private boolean b = false;
 
 //定义生产方法
 public  synchronized void proc(){//是不是先生产,后消费,但是count已经为1了,那还是先生产吗??????
 while(b){//这里是不是b为true就等待,如果不为true,就执行while后面程序。
 try{this.wait();}catch(InterruptedException e){}
 }
 this.name  ="智能手机  生产第 "+ count+"个";
 System.out.println(Thread.currentThread().getName()+this.name);
 count++;//如果这里先累加,后输出生产几个语句的话,是不是count可以设为1?????????????
 b = true;
 this.notifyAll();
 }
 //定义消费方法
 public synchronized void cus(){
 while(!b){
 try{this.wait();}catch(InterruptedException e){}
 }
 System.out.println(Thread.currentThread().getName()+"  "+"消费第   "
 +this.name);
 b = false;
 this.notifyAll();
 }
 }
 //生产者类
 class Producter implements Runnable{
 private Product p;
 Producter(Product p) {this.p = p;}
 public void run(){
 while(true){
 p.proc();
 }
 }
 }
 //消费者类
 class Customer implements Runnable{
 private Product p;
 Customer(Product p) {this.p = p;}
 public void run(){
 while(true){
 p.cus();
 }
 }
 }
 public class ProductCustomThread {
 public static void main(String[] args) {
 Product p = new Product();//产品对象
 Producter pd = new Producter(p);//生产者对象
 Customer ct = new Customer(p);//消费者对象
 
 Thread t1 = new Thread(pd);
 Thread t2 = new Thread(ct);
 
 
 Thread t3 = new Thread(pd);
 Thread t4 = new Thread(ct);
 
 Thread t5 = new Thread(pd);
 Thread t6 = new Thread(ct);
 
 Thread t7 = new Thread(pd);
 Thread t8 = new Thread(ct);
 t1.start();
 t2.start();
 t3.start();
 t4.start();
 t5.start();
 t6.start();
 t7.start();
 t8.start();
 
 
 }
 }
 //哪位大侠能讲下这个逻辑,有点迷糊b的作用
 
 
 |