Java 多线程之--- Thread.join介绍

许久许久没有写过博客了,以前上班总是没有时间,但是总感觉写博客还是很好的一种记录自己技术进程的一种方式

于是在辞职后来到北软,又一次上学了,又一次有时间来写博客了,所以再次开始写博客了,呵呵,再次当学生的感觉

真好!!!!


这次说的是Thread的join方法,以前总是使用他的run和sleep方法,哪两个都是比较清楚的,对于这个join方法,他的

主要功能就是,当你在一个方法里面调用其他的线程的时候,如果使用了类似thread1.join(),这样的话,这个调用的线程

就开始一直等待thread1这个线程返回,什么时候thread1这个线程的run方法运行完了返回了,这个当前的主线程才会继

续向下运行。当然,join还有两个参数方法,这个参数的意思就是,首先等待这个线程调用完,比如

thread1.sleep(1000),这样主线程就会等待thread1运行,直到thread1运行完返回或者当前主线程等待超过1秒钟就会不

理这个thread1线程继续向下执行。代码如下


package com.bird.concursey;

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

/**
 * 数据源
 * @author bird
 * 2014年9月15日 下午10:10:04
 */
public class DataSourceLoader implements Runnable{

	public void run() {
		System.out.println("begining the data source loding" + new Date());
		try {
			TimeUnit.SECONDS.sleep(4);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("begining the data source loding" + new Date());
	}
	
	public static void main(String[] args) {
		DataSourceLoader dsLoader = new DataSourceLoader();
		Thread thread1 = new Thread(dsLoader, "dsloader");
		NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader();
		Thread thread2 = new Thread(ncLoader, "ncloader");
		thread1.start();
		thread2.start();
		try {
			thread1.join();
		//	thread2.join(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(new Date());
	}
}



package com.bird.concursey;

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

public class NetworkConnectionsLoader implements Runnable {

	public void run() {
		System.out.println("begining the data source loding" + new Date());
		try {
			TimeUnit.SECONDS.sleep(6);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("begining the data source loding" + new Date());
	}

}

begining the data source lodingMon Sep 15 22:27:41 CST 2014
begining the data source lodingMon Sep 15 22:27:41 CST 2014
begining the data source lodingMon Sep 15 22:27:45 CST 2014
Mon Sep 15 22:27:46 CST 2014
begining the data source lodingMon Sep 15 22:27:47 CST 2014







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值