package thread;public class Test {
public static void main(String[] args) {
Queue q=new Queue();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}}
class Producer extends Thread{
Queue q;
public Producer(Queue q) {
this.q=q;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Producer put:"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
class Consumer extends Thread{
Queue q;
Consumer(Queue q){
this.q=q;
}
@Override
public void run() {
while (true){
System.out.println("Consumer get:"+q.get());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Queue{
int value;
public void put(int i){
this.value=i;

}
public int get(){
return value;
}

}我都让Producer线程睡眠那么久了 
搞不懂为什么Consumer线程的get 一直是0?顺便求前辈们说一下 wait 和notify的用法 调用的时候 必须要显示用this 或者引用变量 .  来调用么··我看孙鑫老师的视频 没有加 直接用的wait 和notifyjava  多线程 线程安全

解决方案 »

  1.   

    class Producer extends Thread{     Queue q;     public Producer(Queue q) {         this.q=q;     }     @Override    public void run() {             for (int i = 0; i < 10; i++) {                 System.out.println("Producer put:"+i);                 try {                     Thread.sleep(500);                 } catch (InterruptedException e) {                     e.printStackTrace();                 }             }                   } } 
    看你生产者的代码,哪里有给Queue的q添加值了呢? 
      

  2.   

    在Producer里面没有调用Queue类里面的put方法。取出来的肯定是0.
      

  3.   

    第21行有问题,     System.out.println("Producer put:"+i);   没有给put()值进去。还有就是即使你这个put()值进去了,你没有对线程进行安全控制访问,会出现线程安全问题的