什么是Race Condition
首先,什么是Race Condition呢,Race Condition中文翻译是竞争条件,是指多个进程或者线程并发访问和操作同一数据且执行结果与访问发生的特定顺序有关的现象。换句话说,就是线程或进程之间访问数据的先后顺序决定了数据修改的结果,这种现象在多线程编程中是经常见到的。
Race Condition 实例
class MyThread implements Runnable {
/**
* 计算类型,1表示减法,其他的表示加法
*/
private int type;
public MyThread(int type) {
this.type = type;
}
public void run() {
if (type == 1)
for (int i = 0; i < 10000; i++)
Test.num--;
else
for (int i = 0; i < 10000; i++)
Test.num--;
}
}
public class Test {
public static int num = 1000000;
public static void main(String[] args) {
Thread a = new Thread(new MyThread(1));
Thread b = new Thread(new MyThre