java 多线程的join学习
前言
第一次看到join ,以为是数据库的join , 最后才搞清楚,官网的介绍是:
join public final void join (long millis )throws InterruptedException Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
正文
这个知识点比较容易理解,直接应用其他网站的代码+我的注释;主要作为备忘录;
package mythread;
public
class
JoinThread extends Thread {
public
static
int
n = 0;
static
synchronized
void
inc() {
n++;
}
public
void
run(){
for
(
int
i = 0; i < 10; i++)
try
{
inc();
sleep(3); 延迟3秒
}
catch
(Exception e){ }
}
public
static
void
main(String[] args) throws Exception {
Thread threads[] =
new
Thread[100];
for
(
int
i = 0; i < threads.length; i++)
// 建立100个线程
threads[i] =
new
JoinThread();
for
(
int
i = 0; i < threads.length; i++)
// 运行刚才建立的100个线程
threads[i].start();
if
(args.length > 0)
for
(
int
i = 0; i < threads.length; i++)
// 100个线程都执行完后继续
threads[i].join();
//下面文字进行解释:
System.out.println(
"n="
+ JoinThread.n);
}
}
threads[i].join():当main 方法有string 参数的时候,才会进入这个循环,每次循环会问:threads[1]这个线程是否执行完,执行完后,再进入for,再问threads[2]是否执行完,当全部执行完100个线程之后才会输入N的最后的值(System.out.println(
"n="
+ JoinThread.n);
);这样确保所有的线程都执行完;
总结:
join方法的功能就是使异步执行的线程变成同步执行。也就是说,当调用线程实例的start方法后,这个方法会立即返回,如果在调用start方法后需要使用一个由这个线程计算得到的值,就必须使用join方法。如果不使用join方法,就不能保证当执行到start方法后面的某条语句时,这个线程一定会执行完。而使用join方法后,直到这个线程退出,程序才会往下执行