出问题了,共享变量
我们先来看一段代码
public class Main {
public static void main(String[] args) throws InterruptedException {
TheThread theThread1=new TheThread();
TheThread theThread2=new TheThread();
theThread1.start();
theThread2.start();
}
static int i = 0;
public static class TheThread extends Thread{
public void run(){
for(;i<100;){
i&#43;&#43;;
System.out.println(Thread.currentThread().getId()&#43;":"&#43;i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
这个运行的最终结果本来应该是200&#xff0c;但是结果远远小于200&#xff0c;如果循环次数越多&#xff0c;则结果差距越大&#xff0c;这是为什么呢&#xff1f;
当一个线程区访问这个变量的时候&#xff0c;另外的线程也可以访问&#xff0c;在修改值得时候&#xff0c;存在同时修改的可能性&#xff0c;这时候i只能被赋值一次&#xff0c;这就导致了一个问题。这个问题我们叫做线程安全问题。这个变量我们称作共享变量。
思考怎样才能防止出现线程安全问题。