Foo类实现了Runnable接口publicclassFooimplementsRunnable{privatebooleanisRun;@Overridepublicvoidrun(){isRun=true;while(isRun){System.out.println("runing......");}}publicvoidstop(){this.isRun=false;}@OverridepublicStringtoString(){return"Foo{"+"isRun="+isRun+'}';}}测试类publicclassThreadTest{publicstaticvoidmain(String[]args){Foof=newFoo();Threadt=newThread(f);t.start();f.stop();System.out.print(f);}}为什么执行了stop()方法之后,t线程没有停止执行呢。我debug发现thread在运行start()方法之前,里面的Foo对象和执行stop()方法的Foo对象是同一个。按理说执行stop()方法后。f的isRun被设置成了false,线程读取到该变量变成false应该停止才对。看thread的源码求大神解答。
2 回答
神不在的星期二
TA贡献1963条经验 获得超6个赞
t.start();并不是离开执行run方法,而是交给OS去调度。针对你这个例子,执行的顺序是f.stop()-->System.out.print(f)也及时调用f对象的toString,然后才开始线程执行。而在你的run方法中又设置isRun=true;所以线程无法停止。修改Foo如下:publicclassFooimplementsRunnable{privateintisRun=1;@Overridepublicvoidrun(){System.out.println("isRunValue:"+isRun);isRun=0;while(isRun==0){System.out.println("runing......");try{Thread.sleep(1000l);}catch(Exceptione){}}}publicvoidstop(){this.isRun=2;}@OverridepublicStringtoString(){return"Foo{"+"isRun="+isRun+"}\n";}}这个时候你会看到类似这样的输出Foo{isRun=2}isRunValue:2runing......runing......runing......runing......说明stop确实在run之前先执行
守着星空守着你
TA贡献1799条经验 获得超8个赞
因为你这是死循环while(isRun){System.out.println("runing......");}而且isRun一直是true,你应该改成:@Overridepublicvoidrun(){//isRun=true;while(isRun){System.out.println("runing......");}}isRun一开始就初始化,应该这么写:publicclassFooThreadimplementsRunnable{privatebooleanisRun=true;@Overridepublicvoidrun(){System.out.println("runbegin...");//isRun=true;while(isRun){System.out.println("runing......");}}publicvoidstop(){System.out.println("callstop");this.isRun=false;}@OverridepublicStringtoString(){return"Foo{"+"isRun="+isRun+'}';}publicstaticvoidmain(String[]args){FooThreadf=newFooThread();Threadt=newThread(f);t.start();try{Thread.sleep(100);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}f.stop();System.out.print(f);}}最终输出:runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......runing......callstopFoo{isRun=false}
添加回答
举报
0/150
提交
取消