JAVA:Volatile、Synchronized—解决线程安全问题:保证内存可见性

该博客探讨了Java中线程安全问题,特别是内存可见性和原子性。通过示例代码展示了非线程安全的`ThreadSafe`类,然后分别使用`Volatile`和`Synchronized`来解决这个问题。`Volatile`确保了变量在多个线程间的内存可见性,但不保证原子性,而`Synchronized`则同时提供了内存可见性和原子性,保证了线程安全。
摘要由CSDN通过智能技术生成

 线程安全问题:内存可见性

public class ThreadSafe {
    //此时线程2将f改成true,但线程1看不到;会一直循环在while (!f)里
    static boolean f=false;   
    public static void main(String[] args) {
        Thread thread1=new Thread(()->{
            System.out.println("启动");
            while (!f){

            }
            System.out.println("结束");
        });
        thread1.start();

        Thread thread2=new Thread(()->{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            f=true;


        });
        thread2.start();
    }

}

解决上面的线程安全问题:

1.利用 Volatile:保证内存可见性,但不保证原子性

public class Volatile {
    

    //此时线程2将f改成true,线程1可看到;不会一直循环在while (!f)里,会输出“结束”
    volatile static boolean f=false;

    public static void main(String[] args) {
        Thread thread1=new Thread(()->{
            System.out.println("启动");
            while (!f){

            }
            System.out.println("结束");
        });
        thread1.start();

        Thread thread2=new Thread(()->{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            f=true;


        });
        thread2.start();
    }

}

2.利用 Synchronized:保证内存可见性、

还可保证原子性https://blog.csdn.net/xhhhx_/article/details/124127014

public class Synchronized {
     static boolean f=false;
    public static void main(String[] args) {
        Object object=new Object();
        //当线程2将f改成true,线程1可看到
        Thread thread1=new Thread(()->{
            System.out.println("启动");
           while (true){
               //在线程2没修改f之前,线程1会重复进行加锁、放锁操作;每次加锁利用synchronized,都会从主内存拷贝变量f的最新副本到工作的内存,
                synchronized (object) {
                    if(f){
                        System.out.println("结束");
                        break;  //跳出while循环
                    }
                }
                //释放了锁,还在while循环里
            }
        });
        thread1.start();

        Thread thread2=new Thread(()->{
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            f=true;
        });
        thread2.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值