A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 云中游 初级黑马   /  2013-7-26 19:29  /  1687 人查看  /  9 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


public class ProCon {

        /**
         * @param args
         */
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                Thing thing = new Thing();
                Producer p = new Producer(thing);
                Consumer s= new Consumer(thing);
            new Thread(p).start();
            new Thread(s).start();
        }

}


class Thing{
        private String name=null;
        private int counter=1;
        private boolean flag=false;

        public synchronized  void pro(String name)
        {
                if(flag)
                        try{this.wait();}catch(Exception e){}
                this.name =name+counter++;
                System.out.println("生产---"+this.name);
                flag=true;
                notify();
        }
        public synchronized void out()
        {
                if(!flag)
                        try{this.wait();}catch(Exception e){}
                System.out.println("消费++++"+this.name);
                flag=false;
                notify();
        }
}
class Producer implements Runnable{
private Thing t=null;
        public Producer(Thing t)
        {
                this.t=t;
               
        }
        @Override
        public void run() {
                // TODO Auto-generated method stub
                while(true){
                t.pro("商品");
                }
        }
}
class Consumer implements Runnable{
        private Thing t=null;
        public Consumer(Thing t)
        {
                this.t=t;
               
        }
        @Override
        public void run() {
                // TODO Auto-generated method stub
                while(true){
                t.out();
                }
        }
       
       
}


我想问的就是为什么在run方法里面为什么必须的加while(true){}来访问方法   不然只分别生产和消费一次,那个线程不是一直运行的么。为何还要加while语句了??、求大神指导

9 个回复

倒序浏览
技术看不懂。。
回复 使用道具 举报
学习学习!
回复 使用道具 举报
加点人气!!
回复 使用道具 举报
while(true){}   这个条件一直是为真的    就是说里面的代码会被一直调用的   
会无限循环下去
回复 使用道具 举报
   你这样想    这个多线程想象成IO流一样   如果只是if  那么他就会被阻塞只能执行当次的任务   像学其他的循环一样,  如你设置为while  或者for   他就会一直循环下去,如果你不设置为while     那么他只运行当前这一次,而下一次的就被阻塞了,需要得到操作权才可以继续执行
回复 使用道具 举报
顶楼上,受教了,谢谢
回复 使用道具 举报
感谢分享
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马