classStopTesterimplementsRunnable{//privatevolatilebooleanstop=false;privatebooleanstop=false;publicvoidstopMe(){stop=true;}@Overridepublicvoidrun(){while(!stop){}System.out.println("Threadstopped.");}}publicclassTestVolatile{publicstaticvoidmain(String[]args)throwsException{StopTestertester=newStopTester();Threadthread=newThread(tester);thread.start();Thread.sleep(1000);System.out.println("Trystop...");tester.stopMe();Thread.sleep(1000);}}如果用了volatile,Threadstopped.就可以顺利输出,如果不用就无法输出,何解?tester.stopMe()这行代码是运行在主线程还是运行在thread线程呢?
森栏
相关分类