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();
}
}
}
}