日期:2014-05-20  浏览次数:20810 次

wait 和notify的解惑
下面是生产者消费者的问题,我想问下
Java code

public class ProducerConsumer {
    public static void main(String[] args) {
        [color=#FF0000]SyncStack ss = new SyncStack();
        Producer p = new Producer(ss);
        Consumer c = new Consumer(ss);
        new Thread(p).start();
        new Thread(c).start();[/color]    }
}

class WoTou {
    int id; 
    WoTou(int id) {
        this.id = id;
    }
    public String toString() {
        return "WoTou : " + id;
    }
}

class SyncStack {
    int index = 0;
    WoTou[] arrWT = new WoTou[6];
    
    public synchronized void push(WoTou wt) { //生产方法
        [color=#FFFF00]while(index == arrWT.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }[/color]        this.notifyAll();        
        arrWT[index] = wt;
        index ++;
    }
    
    public synchronized WoTou pop() {
        while(index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        index--;
        return arrWT[index];
    }
}

class Producer implements Runnable {
    SyncStack ss = null;
    Producer(SyncStack ss) {
        this.ss = ss;
    }
    
    public void run() {
        for(int i=0; i<20; i++) {
            WoTou wt = new WoTou(i);
            ss.push(wt);
System.out.println("生产了:" + wt);
            try {
                [color=#0000FF]Thread.sleep((int)(Math.random() * 200));[/color]
            } catch (InterruptedException e) {
                e.printStackTrace();
            }            
        }
    }
}

class Consumer implements Runnable {
    SyncStack ss = null;
    Consumer(SyncStack ss) {
        this.ss = ss;
    }
    
    public void run() {
        for(int i=0; i<20; i++) {
            WoTou wt = ss.pop();
System.out.println("消费了: " + wt);
            try {
                [color=#0000FF]Thread.sleep((int)(Math.random() * 1000));[/color]
            } catch (InterruptedException e) {
                e.printStackTrace();
            }            
        }
    }
}


上面的红字部分不是启动了两个线程的?一个是生产的线程,一个是消费的线程?
启动之后分别执行其重写的run()方法,蓝色的字的部门
生产的速度比消费的速度快多了,然后黄色的字的部门,index == arrWT.length了,wait了
这个时候我是不是线程等待了(这里假设为线程A),释放了对象锁?然后要是有另外的线程B要是再进来了push方法,判断index != arrWT.length了,就执行了下面的notify()方法了,让上面的进程A解锁了???是不是这样的执行过程???????


先回答下上面的问题,还有个问题就是我只创建了一个生产线程,哪里会来两个生产线程A,B来完成上面的操作呢?

------解决方案--------------------
wait() 是等待,notify()是唤醒...
------解决方案--------------------
wait()是线程暂停。notify()是线程唤醒。
都是Object类的方法。任何对象类型都可以继承此两种方法。
至于红字。。。没看到。。。
------解决方案--------------------
从代码上看,好像是两个线程交替进行?
------解决方案--------------------
探讨
上面的红字部分不是启动了两个线程的?一个是生产的线程,一个是消费的线程?

------解决方案--------------------
这个是马老师的视频里的程序
看视频应该就清楚了