join()的作用是等待该线程终止;也就是说,子线程调用join()方法后面的代码,只有等到子线程结束了才能执行。
利用join()方法可以将交替执行的线程合并成为顺序执行的线程,比如在线程B中调用了线程A的join()方法,则直到线程A执行完毕后,才会继续执行线程B。
void |
join()
Waits for this thread to die.
|
void |
join(long millis)
Waits at most
millis milliseconds for this thread to die.
|
void |
join(long millis, int nanos)
Waits at most
millis milliseconds plus
nanos nanoseconds for this thread to die.
|
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()方法时,必须能够拿到该线程对象的锁。
如下代码:
import java.lang.*; import java.util.*; public class JoinTest implements Runnable{ public static int counter = 0; public void run(){ for (int i = 0; i < 10; i++){ counter++; } } public static void main(String args[]) throws Exception{ Runnable r = new JoinTest(); Thread t = new Thread(r); t.start(); System.out.println(counter); } }
调用join()方法可以保证每次输出的结果都是10.
import java.lang.*; import java.util.*; public class JoinTest implements Runnable{ public static int counter = 0; public void run(){ for (int i = 0; i < 10; i++){ counter++; } } public static void main(String args[]) throws Exception{ Runnable r = new JoinTest(); Thread t = new Thread(r); t.start(); t.join(); System.out.println(counter); } }