[置顶] 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();
		}
	}





你可能感兴趣的:(java,并发)