public class Visibility { private static boolean stop; public static void main(String[] args) throws Exception { new Thread(new Runnable(){ public void run() { int i = 0; while(!stop) { i++; } System.out.println("finish loop,i=" + i); } }).start(); Thread.sleep(1000); stop = true; Thread.sleep(2000); System.out.println("finish main"); } }//源代码片段来自云代码http://yuncode.net