Java控制併發 AtomicBoolean Lock Volatile

一、作爲開關

a.   AtomicBoolean

	private AtomicBoolean update = new AtomicBoolean(false);
	public void init()
	{
	   if( this.update.compareAndSet(false, true) )
	   {
		   try{
			// do some thing
		   }
		   finally{
			this.refresh.set(false);
		   }
	   }
	}
b.   volatile

	public volatile boolean update = false;
	public void init()
	{
	    if( update == false ){
	        update = true;
	        // dp some thing
	    }
	}

二,計數器

a.AtomicInteger 

	private static  AtomicInteger a = new AtomicInteger(0);
	a.getAndIncrement();


b.sychrognized + volatile

	private volatile int value;
	public int getValue() { return value; }

    public synchronized int increment() {
        return value++;
    }

疑問:這裏把volatile 關鍵字去掉會有什麼不一樣嗎???

回答:不可以,去掉的時候,多線程的時候,其他的線程會讀到緩存在寄存器的值


三、用Lock

	private Lock lock = new ReentrantLock();
	public void m1(){
		this.lock.lock(); 
		try{
			//do some thing
		}finally{
			lock.unlock();
		}
	}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章