1. Change to static also not private static Boolean isrunning = true; The volatile keyword is primarily used for the visibility of thread variables between multiple threads
1 Public classRunthreadextendsthread{2 Private volatile BooleanIsRunning =true;3 Public voidSetrunning (Booleanisrunning) {4System.out.println (Thread.CurrentThread (). GetName () + Thread setrunning);5 This. isrunning =isrunning;6 }7 8 Public voidrun () {9System.out.println (Thread.CurrentThread (). GetName () + "Enter the Run method ...");Ten while(isrunning) { One //System.out.println (Thread.CurrentThread (). GetName () + "thread isrunning"); A } -System.out.println (Thread.CurrentThread (). GetName () + "thread termination"); - } the - Public Static voidMain (string[] args)throwsException { -Runthread RT =NewRunthread (); - Rt.start (); +Thread.Sleep (3000); -Rt.setrunning (false); +System.out.println (Thread.CurrentThread (). GetName () + "thread isrunning value is set to False"); AThread.Sleep (100); atSystem.out.println (Thread.CurrentThread (). GetName () + "::" +rt.isrunning); - } - /*without the volatile keyword, the isrunning in the main memory will not be refreshed and will always be true. So the thread does not terminate, plus it flushes the working memory variables of the RT thread to the main memory - * Thread-0 into the Run method ... - Main thread setrunning - main thread isrunning value is set to False in Main::false - */ to}
View Code
Multi-Threaded 7---The volatile keyword, flushes the thread workspace memory into main memory, that is, stays in sync