遇到难题了,请帮我看看为什么要这么用?有关线程的难题
public class TestPC {public static void main(String[] args){
SynStack ss=new SynStack();
Producer p=new Producer(ss);
Consumer c=new Consumer(ss);
Thread t1=new Thread(p);
t1.start();
Thread t2=new Thread(c);
t2.start();
}
}
class SynStack {
private String[] date=new String[6];
private int cnt=0;
public synchronized void push(String ch){
while(cnt==date.length){
try{
this.wait();
}catch(Exception e){
e.printStackTrace();
}
}
this.notify();
date[cnt]=ch;
System.out.println("生产完成第"+(cnt+1)+"个商品"+date[cnt]);
++cnt;
}
public synchronized String pop(){
while(cnt==0){
try{
this.wait();
}catch(Exception x){
x.printStackTrace();
}
}
this.notify();
--cnt;
return date[cnt];
}
}
class Producer implements Runnable{
private SynStack ss=null;
public Producer(SynStack ss){
this.ss=ss;
}
public void run(){
String ch;
for(int i=0;i<20;i++){
ch="商品"+(i+1);
ss.push(ch);
}
}
}
class Consumer implements Runnable{
private SynStack ss=null;
public Consumer(SynStack ss){
this.ss=ss;
}
public void run() {
for(int i=0;i<20;i++){
System.out.println("消费完一个商品"+ss.pop());
}
}
}
为是SynStack的类中两个方法中一定要用while而不用if呢?还有this.wait()中的this是指什么 ?this.wait被 叫醒后,为什么马上就是运行while外面的?