一个非常tricky的synchronzed的问题——锁一个栈内本地变量

如果synchronized 锁一个线程的栈空间的变量会如何呢?

/**
 * 卓二妹
 */
public class LockLocalReferrence {
    private Boolean run = true;

    public void run() {
        String lockStr = new String("aa");
        while (run) {
//            synchronized (lockStr) {
                System.out.println(Thread.currentThread().getName() + ": running");
//            }
        }
    }

    public void stop() {
        run = false;
        System.out.println(Thread.currentThread().getName() + ": finish to stop running");
    }


    public static void main(String[] args) {
        LockLocalReferrence lockLocalReferrence = new LockLocalReferrence();
        Thread runThread = new Thread() {
            @Override
            public void run() {
                lockLocalReferrence.run();
            }
        };

        Thread stopThread = new Thread() {
            @Override
            public void run() {
                lockLocalReferrence.stop();
            }
        };
        runThread.start();
        stopThread.start();

    }

}

上面这段代码,先不加synchronzed这一段,会发现偶尔输出是这样的:

Thread-1: finish to stop running
Thread-0: running

Thread-1已经将共享的run置为false了,但是Thread-0还是在running。
显然这时候共享的主存里面的run并没有更新到thread-0的mem cache。

但是如果打开synchronzed 注释的那一句话,即使是锁的栈空间的变量,也会使得线程在进入synchronzed代码段去同步主存到mem cache。这样下面的执行,一定是在finish to stop running 这句之后,就看不到running这句了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值