您的位置:首页 > 编程语言 > Java开发

join()之让线程按顺序执行

2015-08-24 15:01 330 查看

Thread中的join()

主线程创建并启动子线程,如果子线程中要进行大量的耗时运算,主线程往往将在子线程运行结束前结束。如果主线程想等待子线程执行完成后再结束(如,子线程处理一个数据,主线程需要取到这个值),则需要用到join()。

作用是:等待线程对象销毁。

join()在内部使用wait()方法进行等待,sychronized使用“对象监视器”原理。

使所属的线程A正常执行run(),而当前线程B进行无期限的阻塞,等线程A销毁后再继续执行线程B后面的代码。

为受检异常,需要抛出InterruptedException

简单例子

先定义一个Thread类:

/**
* Created by zero on 15-8-24.
*/
public class TestThread extends Thread {
private String mName;
private Thread mNextThread;
public TestThread(String name) {
mName = name;
}
public TestThread(String name,Thread next) {
mName = name;
mNextThread = next;
}
@Override
public void run() {
for (int i = 0 ; i < 3 ; i++) {
System.out.println(mName + ":" + i);
}
//...do something
if (mNextThread != null) {
try {
mNextThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


Main函数:

public static void main(String[] args) {
TestThread A = new TestThread("A");
TestThread B = new TestThread("B",A);
TestThread C = new TestThread("C",B);
TestThread D = new TestThread("D",C);
A.start();
B.start();
C.start();
D.start();
}
//这个时候会按照start的顺序执行


运行结果:

/usr/lib/jvm/jdk1.7.0_55/bin/java

A:0

A:1

A:2

B:0

B:1

B:2

C:0

C:1

C:2

D:0

D:1

D:2

Process finished with exit code 0

分析join源码

//join(),里面调用join(0),有参数则延时执行join()
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;
}
}
}


那么wait() 又是神马?

=.= !!原生函数。

public final native void wait(long timeout) throws InterruptedException;

明白它可以将线程挂起,就OK了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程 Java join