标题:遇到难题了,请帮我看看为什么要这么用?有关线程的难题
取消只看楼主
初学者5
Rank: 1
等 级:新手上路
帖 子:15
专家分:0
注 册:2013-8-9
结帖率:75%
已结贴  问题点数:10 回复次数:0 
遇到难题了,请帮我看看为什么要这么用?有关线程的难题
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外面的?
搜索更多相关主题的帖子: private public 
2013-08-20 22:19



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-419442-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.052819 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved