黑马程序员技术交流社区

标题: java多线程问题 [打印本页]

作者: 云中游    时间: 2013-7-26 19:29
标题: java多线程问题

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语句了??、求大神指导
作者: 冷风.    时间: 2013-7-26 20:19
技术看不懂。。
作者: 851091009    时间: 2013-7-28 22:52
加点人气!!
作者: kuoge110    时间: 2013-7-31 14:41
while(true){}   这个条件一直是为真的    就是说里面的代码会被一直调用的   
会无限循环下去
作者: 坚持。    时间: 2013-7-31 20:59
   你这样想    这个多线程想象成IO流一样   如果只是if  那么他就会被阻塞只能执行当次的任务   像学其他的循环一样,  如你设置为while  或者for   他就会一直循环下去,如果你不设置为while     那么他只运行当前这一次,而下一次的就被阻塞了,需要得到操作权才可以继续执行
作者: 浪无痕-陈文坤    时间: 2013-8-2 13:44
顶楼上,受教了,谢谢




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2