标签:inter for reads trace nta str rup 问题 href
什么叫原子操作?
就 是无法被别的线程打断的操作。要么不执行,要么就执行成功。例如: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);
}
}
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_43650923/article/details/101073502
标签:inter for reads trace nta str rup 问题 href
原文地址:https://www.cnblogs.com/xiaolongxia1922/p/14749932.html