竞态条件
实现一个Runnble接口,如下
/**
* 实现Runnable接口
*/
@Getter
public class CountRunnable implements Runnable {
//对象变量i 初始为10
private int i = 10;
//循环10次,每次把i加1后睡眠100毫秒
@Override
public void run() {
for (int j = 0; j < 10; j++) {
i++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
开启两个线程,对同一个 CountRunnable对象中的i的值进行同时修改,如下
package practice;
/**
* 对同一块数据内存的同时访问
*/
public class Test {
public static void main(String[] args) {
//开启两个线程,对同一对象中的i的值进行同时修改
CountRunnable runnable1 = new CountRunnable();
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable1);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(runnable1.getI());
}
}
结果应为30,但是每次结果并不相同,多为20-30之间。
内存可见性
在计算机系统中,除了内存,数据还会被缓存在CPU的寄存器以及各级缓存中,当访问一个变量时,可能直接从寄存器或者cup缓存中获取,而不一定到内存中去取,当修改一个变量时,也可能是先写到缓存中,稍后才会同步更新到内存中。一个线程对内存的修改,另一个线程看不到,一是修改没有及时同步到内存,二是另一个线程根本就没从内存读。