java线程挂起(join)

1、线程挂起join简介

将另外一个线程join到当前线程,则需要等到join进来的线程执行完才会继续执行当前线程。

thread.join();      //当前线程挂起,调用线程 thread,在thread线程执行完毕之前,当前线程一直挂起不执行。
thread.join(1000);  //当前线程挂起,调用线程 thread,等待 thread 线程,等待时间是1000毫秒,超过这个时间,当前线程进入可运行状态。


2、代码事例

package com.xxx.util;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Date: 15-3-27
 * Time: 上午9:38
 * To change this template use File | Settings | File Templates.
 */
public class ThreadJoin1 implements  Runnable{
    @Override
    public void run() {
        System.out.printf("Beginning threadJoin1 loading:%s\n",new Date());
        try {
            TimeUnit.SECONDS.sleep(6);
        } catch (InterruptedException e) {
            System.out.println("ThreadJoin1 has bean interrupted");
        }
        System.out.println("ThreadJoin1 loading has finished.");
    }
}
package com.xxx.util;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Date: 15-3-27
 * Time: 上午9:38
 * To change this template use File | Settings | File Templates.
 */
public class ThreadJoin2 implements  Runnable{
    @Override
    public void run() {
        System.out.printf("Beginning threadJoin2 loading:%s\n",new Date());
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            System.out.println("ThreadJoin2 has bean interrupted");
        }
        System.out.println("ThreadJoin2 loading has finished.");
    }
}
main类

package com.xxx.util;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Date: 15-3-27
 * Time: 上午9:44
 * To change this template use File | Settings | File Templates.
 */
public class ThreadJoinMain {
    public static void main(String[] args){
        Thread threadJoin1 = new Thread(new ThreadJoin1());
        Thread threadJoin2 = new Thread(new ThreadJoin2());
        threadJoin1.start();
        threadJoin2.start();
        try {
            //main线程等待threadJoin1线程1秒,超过一秒,main线程进入可运行状态
            threadJoin1.join(1000);
            threadJoin2.join();
        } catch (InterruptedException e) {
            System.out.println("Handle InterruptedException.");
        }
        System.out.printf("%s:Configuration has bean loaded:%s\n",Thread.currentThread().getName(),new Date());
    }
}

3、运行结果


4、结论

当前线程挂起等待。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值