多线程之Join方法

来源:互联网 发布:蕾丝内裤淘宝买家秀 编辑:程序博客网 时间:2024/06/04 19:20

线程加入:join()方法,等待其他线程终止。在当前线程中调用另一个线程的join()方法,则当前线程转入阻塞状态,直到另一个进程运行结束,当前线程再由阻塞转为就绪状态。


package thread;public class ThreadJoinTest {/** * @param args */public static void main(String[] args) {ThreadJoin tj = new ThreadJoin();Thread t1 = new Thread(tj);NormalThread nt = new NormalThread(t1);Thread t2 = new Thread(nt);t1.start();t2.start();}}class ThreadJoin implements Runnable {@Overridepublic void run() {for (int i=0;i<10;i++) {System.out.println(Thread.currentThread().getName() + "-->" + i);try {Thread.sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}class NormalThread implements Runnable {private Thread t;NormalThread(Thread t) {this.t = t;}@Overridepublic void run() {for (int i=0;i<10;i++) {System.out.println(Thread.currentThread().getName() + "-->" + i);try {Thread.sleep(500);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if (i == 3) {try {t.join(); // 会使当前线程暂停运行,知道t运行完毕} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}

​运行结果:

Thread-0-->0

Thread-1-->0

Thread-0-->1

Thread-1-->1

Thread-1-->2

Thread-0-->2

Thread-0-->3

Thread-1-->3

Thread-0-->4

Thread-0-->5

Thread-0-->6

Thread-0-->7

Thread-0-->8

Thread-0-->9

Thread-1-->4

Thread-1-->5

Thread-1-->6

Thread-1-->7

Thread-1-->8

Thread-1-->9


0 0