同步死循環

package com.freeflying.thread.volatil;
/**
 * 通過valatile解決同步死循環
 * @ClassName: HandleSyncDeadCycle  
 * @Description:volatile強制從公共堆棧進行取值
 * @author freeflying
 * @date 2018年7月12日
 */
public class HandleSyncDeadCycle {
	public static void main(String[] args) {
		try {
			HandleSyncDeadCycleEx handleSyncDeadCycleEx=new HandleSyncDeadCycleEx();
			handleSyncDeadCycleEx.start();
			Thread.sleep(1000);
			handleSyncDeadCycleEx.setRunning(false);
			System.out.println("value is become false");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
class HandleSyncDeadCycleEx extends Thread{
	volatile private boolean isRunning=true;
	public boolean isRunning() {
		return isRunning;
	}
	public void setRunning(boolean isRunning) {
		this.isRunning=isRunning;
	}
	@Override
	public void run() {
		System.out.println("input run method!");
		while(isRunning==true) {
		}
		System.out.println("Thread is stop!!");
	}
}

結果:

input run method!
value is become false
Thread is stop!!

發佈了64 篇原創文章 · 獲贊 5 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章