public class StopThread {
private static boolean stopRequest;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable(){
public void run(){
int i = 0;
while(!stopRequest)
i++;
}
});
thread.start();
Thread.sleep(1000);
stopRequest = true;
}
}
synchronized的作用不仅仅是控制线程互斥的访问某个对象的方法或者block,而且能够确保之前线程对该对象的修改可见,如上面的例子,按一般来看,应该过1秒左右就应该停止了,但是实际上,它不会停止,因为主线程对stopRequest变量的修改,在另一个线程中不可见。