您的位置:首页 > 其它

thread.join()方法的理解

2017-12-16 16:51 821 查看
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方法后,表示这个主线程愿意等待这个新加入的线程,直到它执行完。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  join