Java的线程的join()方法

Java的线程的join()方法

Java的线程的join()方法是让当前的线程进入Blocked/Waiting状态,让调用该join()的Thread对象执行完毕后,才让当前线程进入Runnable状态,它有三个重载的方法:

public final void join()

该方法就是上文提到的,让当前线程进入Blocked/Waiting状态,让调用join()的Thread对象进入Dead状态之后,当前线程才能进入Runnable状态。

public final synchronized void join(long millis)

该方法让当前线程等待调用join(long t)的Thread对象t毫秒之后,或者等待该Thread对象进入Dead状态后,该线程重新进入Runnable状态,由于线程的执行依赖于OS的实现方法,我们并不能保证让当前线程等待我们所指定的时间。

public final synchronized void join(long millis, int nanos)

与上述方法一致,只不过加入纳秒而已。

package Test;

/**
 * Created by siege on 2015-09-13.
 */
public class ThreadJoinExample{
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable(), "t1");
        Thread t2 = new Thread(new MyRunnable(), "t2");
        Thread t3 = new Thread(new MyRunnable(), "t3");

        t1.start();

        //等t1执行完毕或者2秒后,再开始t2线程。
        try {
            t1.join(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t2.start();

        //t1线程执行完毕后再开始t3线程
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t3.start();

        //让t1,t2,t3执行完毕之后,再执行main线程
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("All threads are dead, exiting main thread");
    }

}

class MyRunnable implements Runnable{

    @Override
    public void run() {
        System.out.println("Thread started:::"+Thread.currentThread().getName());
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread ended:::"+Thread.currentThread().getName());
    }

}

执行结果:

Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值