thread.join()方法的理解

本文通过两个Java示例程序探讨了并发编程中变量可见性的问题。第一个程序因缺乏同步机制导致输出结果通常为0或很小的数字;第二个程序通过使用join方法确保了线程间的正确同步,使最终输出接近预期的2000。文章深入浅出地解释了volatile关键字的作用及join方法如何解决可见性问题。

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

1。问题由来(这个程序得到的结果是0)

package com.haut.thread;

/**
 * @author shuiyu_lei
 * @date 2017/12/16
 */
public class AccountingVol implements Runnable {

    static AccountingVol accountingVol = new AccountingVol();
    static volatile int i = 0;

    public static void increase() {
        i++;
    }


    @Override
    public void run() {
        for (int j = 0; j < 1000; j++) {
            increase();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(accountingVol);
        Thread thread1 = new Thread(accountingVol);
        thread.start();
        thread1.start();
        System.out.println(i);
    }
}

2继续看,现在程序得到的值小于2000

package com.haut.thread;

/**
 * @author shuiyu_lei
 * @date 2017/12/16
 */
public class AccountingVol implements Runnable {

    static AccountingVol accountingVol = new AccountingVol();
    static volatile int i = 0;

    public static void increase() {
        i++;
    }


    @Override
    public void run() {
        for (int j = 0; j < 1000; j++) {
            increase();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(accountingVol);
        Thread thread1 = new Thread(accountingVol);
        thread.start();
        thread1.start();
        thread.join();
        thread1.join();
        System.out.println(i);
    }
}

3。理解如果不使用join方法,得到的i基本上是0或者 很小的数字,因为thread和thread1线程可能还没开始运行地,主线程程序就把i的值输出了,使用了join方法后,表示这个主线程愿意等待这个新加入的线程,直到它执行完。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

wending-Y

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值