Keyword volatile first experience

package com.dq;

public class ThreadTest 
{
	// 这里必须加上volatile关键字,否则程序听不下来
	public static volatile boolean flag = true; 
	
	public static class MyThread extends Thread
	{
		@Override
		public void run() 
		{
			System.out.println("进入线程执行体");
			while(flag)
			{
				// 这里空跑
			}	
			System.out.println("走出线程执行体");
		}
	}
	
	public static void main(String[] args) throws InterruptedException 
	{
		new MyThread().start();
		Thread.sleep(10);
		flag = false; // 只有加上volatile关键字这里的修改才会马上同步到主内存,MyThread线程才会看到
	}
}

Published 236 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/gunsmoke/article/details/104739481