@ZeroGeek
2015-08-24T07:00:06.000000Z
字数 1548
阅读 821
Java
先定义一个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 < 5 ; 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(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;
}
}
}
=.= !!原生函数。
public final native void wait(long timeout) throws InterruptedException;
明白它可以将线程挂起,就OK了。