最近发现曾经看过的很多东西,因为项目中用不到,而慢慢淡忘了,遂将自己自学到的对知识点的理解,点点滴滴记录到博客。
JOIN
public final void join(long millis) throws InterruptedException
-
等待该线程终止的时间最长为
millis
毫秒。超时为0
意味着要一直等下去。 -
-
参数:
-
millis
- 以毫秒为单位的等待时间。
抛出:
-
InterruptedException
- 如果任何线程中断了当前线程。当抛出该异常时,当前线程的 中断状态 被清除
-
根据API文档,字面意思可以看出这个方法的作用。等待目标线程终止。
—————————————————————下面的是代码 华丽的分割线————————————————————
package com.test.laboratory;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLException;
import javax.swing.plaf.SliderUI;
public class ThreadJoinTest1 implements Runnable{
@Override
public void run() {
String myProcessName = Thread.currentThread().getName();
for (int i = 0; i < 5; i++) {
System.out.println(myProcessName+" "+i);
try {
TimeUnit.SECONDS.sleep(1);
//2.因为t1.join,t1线程启动,t1运行到这,休眠一秒。
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException { //程序入口,让我们从这里开始看起
Thread t1 = new Thread(new ThreadJoinTest1());
Thread t2 = new Thread(new ThreadJoinTest2());
String myProcessName = Thread.currentThread().getName();
System.out.println(myProcessName+" start");
t1.start();
t2.start();
t1.join();
//1.Main线程将t1、t2线程启动后,执行到了t1.join。[这将代表Main线程会一直等待到t1线程完全运行完毕后,才会继续往下运行Main线程的代码]
System.out.println(myProcessName+" end");
}
}
class ThreadJoinTest2 implements Runnable{
@Override
public void run() {
String myProcessName = Thread.currentThread().getName();
System.out.println(myProcessName+" start");
//3.因为t1线程正在休眠一秒,而Main线程将一直等待t1运行完才会继续运行,所以资源分配给了唯一空闲的t2
try {
TimeUnit.SECONDS.sleep(1);
//4.t2休眠,资源公平竞争,分配给t1,后面就是循环直至代码运行完毕
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(myProcessName+" end");
}
}
运行结果:
main start
Thread-0 0
Thread-1 start
Thread-0 1
Thread-1 end
Thread-0 2
Thread-0 3
Thread-0 4
main end
从上述代码可以看出几个结论:
1.A线程使用了B.join()时,将代表A线程一直等待B线程,直至B线程运行完毕。才会继续执行A
2.当A等待B线程时,除A以外的所有线程自由竞争资源。
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;//计算剩余等待时间
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base; //计算join开始执行开始,占用的时间。
}
}
}
补充:3.根据join的源码,A线程使用B.join()时,必须获取B的锁,才可以执行join。
总结:一句话描述Thread.join(),A线程执行B.join(),就是A不停执行B.isAlive(),如
果B存活,那么A反复执行wait(0).让A等待。