黑马程序员技术交流社区

标题: 线程问题 [打印本页]

作者: @ne_pie尒ce    时间: 2013-11-22 11:24
标题: 线程问题
package com.itheima;
public class ProducerConsumerDemo {
public static void main(String[] args) {
  Resource r=new Resource();
  
  Producer p=new Producer(r);
  Consumer c=new Consumer(r);
  Thread t1=new Thread(p);
  Thread t2=new Thread(c);
  t1.start();
  t2.start();

}
}
class Resource{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void produce(String name){
  
  if (flag)
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  this.name=name+":"+(count++);
  System.out.println(Thread.currentThread().getName()+"生产"+this.name);
  flag=true;
  this.notify();
}
public synchronized void out(){
  if (!flag)
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  System.out.println(Thread.currentThread().getName()+"......消费....."+this.name);
  flag=false;
  this.notify();
   
}
}
class Producer implements Runnable{
private Resource r;
public Producer(Resource r) {
  this.r=r;
}
@Override
public void run() {
  while (true) {
   r.produce("商品");
  }
  
}

}
class Consumer implements Runnable{
private Resource r;
    public Consumer(Resource r) {
  this.r=r;
}
@Override
public void run() {
  // TODO Auto-generated method stub
  while (true) {
   r.out();
  }
}

}
运行结果:
Thread-0生产商品:34939
Thread-1......消费.....商品:34939
Thread-0生产商品:34940
Thread-1......消费.....商品:34940
Thread-0生产商品:34941
Thread-1......消费.....商品:34941
Thread-0生产商品:34942
Thread-1......消费.....商品:34942
Thread-0生产商品:34943
Thread-1......消费.....商品:34943
Thread-0生产商品:34944
Thread-1......消费.....商品:34944
怎么不是从1开始生产?

作者: 樊志伟    时间: 2013-11-22 18:13
我的是从1开始的。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2