Java并发编程入门 互动版

出问题了,共享变量

我们先来看一段代码

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++;
                System.out.println(Thread.currentThread().getId()+":"+i);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这个运行的最终结果本来应该是200,但是结果远远小于200,如果循环次数越多,则结果差距越大,这是为什么呢?

当一个线程区访问这个变量的时候,另外的线程也可以访问,在修改值得时候,存在同时修改的可能性,这时候i只能被赋值一次,这就导致了一个问题。这个问题我们叫做线程安全问题。这个变量我们称作共享变量。

思考怎样才能防止出现线程安全问题。