[关闭]
@ZeroGeek 2015-08-24T07:00:06.000000Z 字数 1548 阅读 718

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

Java


Thread中的join()

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

简单例子

先定义一个Thread类:

  1. /**
  2. * Created by zero on 15-8-24.
  3. */
  4. public class TestThread extends Thread {
  5. private String mName;
  6. private Thread mNextThread;
  7. public TestThread(String name) {
  8. mName = name;
  9. }
  10. public TestThread(String name,Thread next) {
  11. mName = name;
  12. mNextThread = next;
  13. }
  14. @Override
  15. public void run() {
  16. for (int i = 0 ; i < 5 ; i++) {
  17. System.out.println(mName + ":" + i);
  18. }
  19. //...do something
  20. if (mNextThread != null) {
  21. try {
  22. mNextThread.join();
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }
  28. }

Main函数:

  1. public static void main(String[] args) {
  2. TestThread A = new TestThread("A");
  3. TestThread B = new TestThread("B",A);
  4. TestThread C = new TestThread("C",B);
  5. TestThread D = new TestThread("D",C);
  6. A.start();
  7. B.start();
  8. C.start();
  9. D.start();
  10. }
  11. //这个时候会按照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源码

  1. //join(),里面调用join(0),有参数则延时执行join()
  2. public final synchronized void join(long millis)
  3. throws InterruptedException {
  4. long base = System.currentTimeMillis();
  5. long now = 0;
  6. if (millis < 0) {
  7. throw new IllegalArgumentException("timeout value is negative");
  8. }
  9. if (millis == 0) {
  10. while (isAlive()) { //关键在这里,如果存活一直等待
  11. wait(0);
  12. }
  13. } else {
  14. while (isAlive()) {
  15. long delay = millis - now;
  16. if (delay <= 0) {
  17. break;
  18. }
  19. wait(delay);
  20. now = System.currentTimeMillis() - base;
  21. }
  22. }
  23. }

那么wait() 又是神马?

=.= !!原生函数。

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

明白它可以将线程挂起,就OK了。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注