synchronized与volatile的区别

1 synchronized与volatile

  • synchronized:保证可见性和原子性,线程安全;
  • volatile:保证可见性,不保证原子性,线程不安全。

可见性:变量值修改后,立即更新到公共内存区,保证其他线程是可见的。
原子性:一个线程从获取变量,到变更结束,不会被其他线程改变。

2 测试

2.1 volatile

package com.monkey.java_study.security;

import java.util.ArrayList;
import java.util.List;

/**
 * 线程安全测试.
 *
 * @author xindaqi
 * @date 2021-10-26 16:27
 */
public class ThreadSecurityTest {

    private volatile int var1;

    private int var2;


    public ThreadSecurityTest() {
    }

    public void setVar1(int var1) {
        this.var1 = var1;
    }

    public int getVar1() {
        return var1;
    }

    public void setVar2(int var2) {
        this.var2 = var2;
    }

    public int getVar2() {
        return var2;
    }

    public void increaseVar1() {
        var1 += 1;
    }

    public void increaseVar2() {
        var2 += 1;
    }

    public static void volatileTest() throws InterruptedException {
        ThreadSecurityTest threadSecurityTest = new ThreadSecurityTest();
        threadSecurityTest.setVar1(0);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread t1 = new Thread(() -> {
                threadSecurityTest.increaseVar1();
                System.out.println(">>>>>>>>>>var1:" + threadSecurityTest.getVar1());

            });
            t1.start();
            threadList.add(t1);
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        System.out.println(">>>>>>>>>>Finally:" + threadSecurityTest.getVar1());

    }

    public static void synchronizedTest() throws InterruptedException {
        ThreadSecurityTest threadSecurityTest = new ThreadSecurityTest();
        threadSecurityTest.setVar2(0);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread t1 = new Thread(() -> {
                synchronized (threadSecurityTest) {
                    threadSecurityTest.increaseVar2();
                    System.out.println(">>>>>>>>>>var2:" + threadSecurityTest.getVar2());
                }
            });
            t1.start();
            threadList.add(t1);
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        System.out.println(">>>>>>>>>>Finally:" + threadSecurityTest.getVar2());
    }

    @Override
    public String toString() {
        return "ThreadSecurityTest{" +
                "var1=" + var1 +
                ", var2=" + var2 +
                '}';
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSecurityTest.volatileTest();
    }
}

由结果可知,使用volatile修饰的变量,无法保证线程安全。

在这里插入图片描述

2.2 synchronized

package com.monkey.java_study.security;

import java.util.ArrayList;
import java.util.List;

/**
 * 线程安全测试.
 *
 * @author xindaqi
 * @date 2021-10-26 16:27
 */
public class ThreadSecurityTest {

    private volatile int var1;

    private int var2;


    public ThreadSecurityTest() {
    }

    public void setVar1(int var1) {
        this.var1 = var1;
    }

    public int getVar1() {
        return var1;
    }

    public void setVar2(int var2) {
        this.var2 = var2;
    }

    public int getVar2() {
        return var2;
    }

    public void increaseVar1() {
        var1 += 1;
    }

    public void increaseVar2() {
        var2 += 1;
    }

    public static void volatileTest() throws InterruptedException {
        ThreadSecurityTest threadSecurityTest = new ThreadSecurityTest();
        threadSecurityTest.setVar1(0);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread t1 = new Thread(() -> {
                threadSecurityTest.increaseVar1();
                System.out.println(">>>>>>>>>>var1:" + threadSecurityTest.getVar1());

            });
            t1.start();
            threadList.add(t1);
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        System.out.println(">>>>>>>>>>Finally:" + threadSecurityTest.getVar1());

    }

    public static void synchronizedTest() throws InterruptedException {
        ThreadSecurityTest threadSecurityTest = new ThreadSecurityTest();
        threadSecurityTest.setVar2(0);
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Thread t1 = new Thread(() -> {
                synchronized (threadSecurityTest) {
                    threadSecurityTest.increaseVar2();
                    System.out.println(">>>>>>>>>>var2:" + threadSecurityTest.getVar2());
                }
            });
            t1.start();
            threadList.add(t1);
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        System.out.println(">>>>>>>>>>Finally:" + threadSecurityTest.getVar2());
    }

    @Override
    public String toString() {
        return "ThreadSecurityTest{" +
                "var1=" + var1 +
                ", var2=" + var2 +
                '}';
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadSecurityTest.synchronizedTest();
    }
}

由测试结果可知,使用synchronized关键字的对象,保证对象属性顺序执行,即线程安全。
在这里插入图片描述

3 小结

  • synchronized线程安全;
  • volatile线程不安全。

【参考文献】
[1]https://www.cnblogs.com/heilyeah/p/6594122.html
[2]https://www.cnblogs.com/xuqiudong/p/3952827.html
[3]https://blog.csdn.net/qq_33591903/article/details/81486754

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值