java中的Volatile与Atomics

Volatile

Volatile保证在变量在多线程的可见性。用于修饰变量。

代码如下:

public class VolatileDemo1 {

	volatile int a;

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}
	
	public void testA1(final VolatileDemo1 vd){
		Thread thread = new Thread(){
			public void run() {
				for (int i=1; i<5; i++) {
					vd.setA(i);
					System.out.println("我被修改为:" + vd.getA());
				}
			}
		};
		thread.start();
	}
	
	public void testA2(final VolatileDemo1 vd){
		Thread thread = new Thread(){
			public void run() {
				System.out.println("我获取到的值:" + vd.getA());
			}
		};
		thread.start();
	}
	
	public static void main(String[] args) {
		VolatileDemo1 vd1 = new VolatileDemo1();
		vd1.testA1(vd1);
		vd1.testA2(vd1);
	}
}

Atomics

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicsDemo {

	private AtomicInteger atomicCount = new AtomicInteger();
	
	private int count = 0;
	public int increase() {
		synchronized (this) {
			count = count + 1;
			return count;
		}
	}
	
	public int decrease() {
		synchronized (this) {
			count = count - 1;
			return count;
		}
	}
	
	public int atomicIncrease() {
		return atomicCount.incrementAndGet();
	}
	
	public int atomicDecrease() {
		return atomicCount.decrementAndGet();
	}
	
	public static void main(String[] args) throws InterruptedException {
		long startTime = System.currentTimeMillis();
		final AtomicsDemo ad = new AtomicsDemo();
		for (int i=0; i<1000; i++) {
			Thread thread = new Thread(){
				public void run() {
					ad.increase();
					//ad.atomicIncrease();

				}
			};
			thread.start();
		}
		TimeUnit.SECONDS.sleep(3);
		System.out.println("时间:" + (System.currentTimeMillis() - startTime));
		System.out.println("count大小:" + ad.count);
		System.out.println("atomicCount大小:" + ad.atomicCount);
		
		System.out.println("=========");
		
		long startTime2 = System.currentTimeMillis();
		//final AtomicsDemo ad = new AtomicsDemo();
		for (int i=0; i<1000; i++) {
			Thread thread = new Thread(){
				public void run() {
					//ad.increase();
					ad.atomicIncrease();

				}
			};
			thread.start();
		}
		TimeUnit.SECONDS.sleep(3);
		System.out.println("时间:" + (System.currentTimeMillis() - startTime2));
		System.out.println("count大小:" + ad.count);
		System.out.println("atomicCount大小:" + ad.atomicCount);
	}
}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。