Thread.sleep() 和 System.out.println() 与内存可见性

本文探讨了在Java多线程环境中,volatile关键字、Thread.sleep()及System.out.println()如何解决线程间的数据同步问题。通过实例演示,volatile确保了内存可见性,使线程能感知到变量的最新状态;而Thread.sleep()和System.out.println()虽无volatile,但通过阻塞和加锁机制同样实现了线程间的正确通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.加上volatile关键字内存可见性,线程t1结束,不加volatile线程t1死循环无法结束。

import java.util.concurrent.TimeUnit;
public class T01_withVolitile {
    private volatile boolean stop=false;
    public static void main(String[] args) throws  Exception{
        T01_withVolitile c = new T01_withVolitile();
        new Thread(()->{
            while (!c.stop){
            }
            System.out.println("线程t1结束");
        },"t1").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            c.stop=true;
        },"t2").start();
    }
}

  2.Thread.sleep()  

与1的区别是没有关键字volatile,循环中加了sleep()语句,线程1可以结束。原因:线程sleep时是阻塞状态,时间结束时变为可运行状态,获得cpu运行权限时从主内存中读取数据,线程1读取到更新后的值跳出循环结束线程。

import java.util.concurrent.TimeUnit;
public class T01_withVolitile {
    private boolean stop = false;
    public static void main(String[] args) throws Exception {
        T01_withVolitile c = new T01_withVolitile();
        new Thread(() -> {
            while (!c.stop) {
                try {
                    Thread.sleep(1);
                } catch (Exception e){}
            } System.out.println("线程t1结束");
        }, "t1").start(); 
        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            c.stop = true;
        }, "t2").start();
    }
}

 3.System.out.println()

 与1的区别是没有关键字volatile 循环中加了打印语句。线程1可以结束。原因:System.out.println()代码是加锁的保证内存可见性

import java.util.concurrent.TimeUnit;
public class T01_withVolitile {
    private  boolean stop=false;
    public static void main(String[] args) throws  Exception{
        T01_withVolitile c = new T01_withVolitile();
        new Thread(()->{
            while (!c.stop){
                System.out.println("a");
            }
            System.out.println("线程t1结束");
        },"t1").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            c.stop=true;
        },"t2").start();
    }
}

​

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值