为什么我的运行结果是 Thread-0---生产者+商品+...1
后面就没了 运行了好多次都是这样 到底是哪里出问题了啊??
- class Goods{
- private String name;
- private int num = 1;
- private boolean flag = false;
- public synchronized void set(String name)
- {
- while(flag)
- try{this.wait();}catch(Exception e){}
- this.name = name+"..."+num++;
- System.out.println(Thread.currentThread().getName()+"---生产者"+this.name);
- flag = true;
- this.notifyAll();
- }
- public synchronized void out()
- {
- while(flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"------消费者"+this.name);
- flag = false;
- this.notifyAll();
- }
- }
- class Producer implements Runnable {
- private Goods g;
- Producer(Goods g)
- {
- this.g = g;
- }
- public void run()
- {
- while(true)
- {
- g.set("+商品+");
- }
- }
- }
- class Consumer implements Runnable{
- private Goods g;
- Consumer(Goods g)
- {
- this.g = g;
- }
- public void run()
- {
- while(true)
- {
- g.out();
- }
- }
- }
- class ProducerConsumerDemo {
- public static void main(String[] args)
- {
- Goods g = new Goods();
- Producer pro = new Producer(g);
- Consumer con = new Consumer(g);
- Thread t1 = new Thread(pro);
- Thread t2 = new Thread(pro);
- Thread t3 = new Thread(con);
- Thread t4 = new Thread(con);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
复制代码 |
|