多线程02-Thread.join

join的使用

作用:保证线程执行结果的可见性

/**
 * @Author: wy
 */
public class MyThread {
    private static Integer i = 1;
    private static Integer j = 2;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            i=j+1;
            j=i;
        });

        Thread thread2 = new Thread(() -> {
            i=3;
            j=i;
        });
        thread1.start(); 
        thread2.start(); 

        Thread.sleep(100);

        System.out.println("i:"+i);
        System.out.println("j:"+j);

    }
}

在以上代码中,按照理想状态如果thread1和thread2按着顺序执行的话,我们的到的结果应该是i=4,j=4。

但是我们知道,我们只是执行了start方法,并不代表线程开始运行,不会立即执行run方法。

此时线程只不过是成为就绪状态,到底哪个线程执行还是要取决于操作系统的调度算法。(window中是抢占式,即哪个线程抢用到cpu后知道线程执行完毕才会释放资源。

linux中为分

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值