什么叫原子操作?
就 是无法被别的线程打断的操作。要么不执行,要么就执行成功。例如:x=3是原子操作。过程就是先把工作内存的x赋成3,再把主存的x赋成3。y=x不是原 子操作,它涉及在工作内存先把x值读出来,再把这个值赋给y。x++或x=x+1也不是原子操作,它涉及取值,自加和赋值。下面我们就用一个例子来说明x ++不是原子操作所带来的问题。
class NumContainer {
int num;
}
class MulThreMarkToWin extends Thread {
NumContainer nc;
public void increase() {
nc.num++;
}
public MulThreMarkToWin(NumContainer nc) {
this.nc = nc;
}
public void run() {
increase();
}
}
public class TestMark_to_win {
public static void main(String[] args) {
NumContainer nc = new NumContainer();
MulThreMarkToWin[] threads = new MulThreMarkToWin[10000];
for (int i = 0; i < 10000; i++) {
threads[i] = new MulThreMarkToWin(nc);
}
for (int i = 0; i < 10000; i++) {
threads[i].start();
}
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(nc.num);
}
}
更多请见:http://www.mark-to-win.com/tutorial/java_6_WhatIsAtomOperation.html