线程安全问题产生的原因和解决方案

1.根本原因:线程的抢占式执行,随机调度。

public class ThreadDemo {
    private static int count;
    static class Counter {
        public static void add() {
            count++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                Counter.add();
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                Counter.add();
            }
        });
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = " + count);
    }
}

这段代码的意思是通过两个线程把count加到10000,可是运行结果总是小于10000的,这就是因为抢占式执行带来的线程安全问题。

2.代码结构:多个线程同时修改同一个变量。

同上代码,两个线程同时修改count变量。

解决方法:修改不同变量

package thread;

public class ThreadDemo {
    private static int count1;
    private static int count2;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    count1++;
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    count2++;
                }
            }
        };
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = " + (count1 + count2));
    }
}

3.原子性:如果修改的操作是原子的,没有问题。如果修改的操作非原子的,出现问题的概率就非常高。(原子:不可拆分的基本单位)

比如count++的++操作本质上要分成三步:

①把内存中的值读取到CPU的寄存器中。load

②把CPU寄存器里的数值进行+1运算。add

③把得到的结果写回到内存中。save

这三个操作是在CPU上执行的机器指令。

 解决原子性问题和解决抢占式问题一样。

通过关键字加锁synchronized,先看一下加锁后原子的执行过程。

 

public class ThreadDemo {
    private static int count;
    static class Counter {
        synchronized public static void add() {
            count++;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                Counter.add();
            }
        });
        t1.start();
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                Counter.add();
            }
        });
        t2.start();
        t1.join();
        t2.join();
        System.out.println("count = " + count);
    }
}

4.内存可见性问题

5.指令重排序。(本质上是编译器优化出bug了)

编译器觉得你写的代码太Ljl了,就把你的代码自作主张的调整了,保持逻辑不变的情况下,进行调整,从而加快程序的执行效率。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值