java线程join()方法分析

join()方法作用就是:当一个线程中调用另一个线程的join()方法时,当前线程会等待另一个线程执行完毕后,在继续执行。起到一种同步的作用。即:若线程A调用线程B的join()方法,那么A会等到B的run()中内容执行完毕再去执行A的run 方法。

package com.zhiru;

class TA implements Runnable {

	private int count = 0;

	@Override
	public void run() {
		//启动线程TA
		System.out.println(Thread.currentThread().getName()+"start...");
		while (count <= 10) {
			System.out.print("count=" + count + " ");
			count++;
		}
		System.out.print("\n");
	}

}

class TB implements Runnable {

	private int id = 0;

	private Thread c;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println(Thread.currentThread().getName()+"start...");
		c=new Thread(new TC());//创建线程TC的对象
		try {
			c.start();
			c.join();//加入线程TC,直到线程TC中的run内容执行完在执行TB的。
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while (id++ <= 10) {
			System.out.print("id=" + id + " ");
		}
		System.out.print("\n");
	}

}
class TC implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		System.out.println("TC was called!"+Thread.currentThread().getName()+"start...");
		for(int i=1;i<=10;i++) System.out.print(i+" ");
		System.out.print("\n");
	}
	
}
public class ThreadJoin {

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		Thread t2=new Thread(new TB());
		Thread t1=new Thread(new TA());
		t2.start();
		t2.join();//直到线程t2执行完在执行t1.
		t1.start();
//		t1.join();
	}

}
Thread-0start...
TC was called!Thread-2start...
1 2 3 4 5 6 7 8 9 10 
id=1 id=2 id=3 id=4 id=5 id=6 id=7 id=8 id=9 id=10 id=11 
Thread-1start...
count=0 count=1 count=2 count=3 count=4 count=5 count=6 count=7 count=8 count=9 count=10 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值