volatile可見性

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Practice17 {

	public static void main(String[] args) {
		ExecutorService es = Executors.newCachedThreadPool();
		AtomicityTest at = new AtomicityTest();
		es.execute(at);
		while (true) {
			int val = at.getValue();
			if (val % 2 != 0) {
				System.out.println(val);
				System.exit(0);
			}
		}

	}

	static class AtomicityTest implements Runnable {

		private int i = 0;

		public int getValue() {
			return i;
		}

		synchronized public void evenIncrement() {
			i++;
			i++;
		}

		@Override
		public void run() {
			while (true) {
				evenIncrement();
			}
		}
	}
}

//output:37


解釋一下:測試原子性概念

在evenIncrement()方法上加了synchronized,只是保證在執行evenIncrement()方法時,不會有其他的線程執行這個方法

如果把i變爲volatile的

private volatile int i = 0;
同樣也不能保證原子性,volatile能保證需要用到i這個變量前是最新的值(就是保證從main memory加載到working memory的值是最新的,但還是不能控制並發)

而i++操作,在線程中會執行以下幾個步驟

1.read (從main memory中讀變量i的值)

2.load(將讀到的值復制到working memory)

3.use(將變量i的值復制到線程執行引擎中)

4.有一個add的操作

5.assign(將完成操作後的變量值i復制到working memory中)

6.store(將變量i從working memory中復制到main memory中,並等待main memory通過write寫入此值)

7.write(寫入)

假如线程1,线程2 在进行read,load 操作中,发现主内存中count的值都是5,那么都会加载这个最新的值

在线程1堆count进行修改之后,会write到主内存中,主内存中的count变量就会变为6

线程2由于已经进行read,load操作,在进行运算之后,也会更新主内存count的变量值为6

导致两个线程及时用volatile关键字修改之后,还是会存在并发的情况。

而上述想要同步 就需要保證對同一數據的讀取和修改只能互斥。

即:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Practice17 {

	public static void main(String[] args) {
		ExecutorService es = Executors.newCachedThreadPool();
		AtomicityTest at = new AtomicityTest();
		es.execute(at);
		while (true) {
			int val = at.getValue();
			if (val % 2 != 0) {
				System.out.println(val);
				System.exit(0);
			}
		}
	}

	static class AtomicityTest implements Runnable {

		private int i = 0;

		public synchronized int getValue() {
			return i;
		}

		synchronized public void evenIncrement() {
			i++;
			i++;
		}

		@Override
		public void run() {
			while (true) {
				evenIncrement();
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值