手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2014-09-16] 来源:Linux社区  作者:Bird [字体:大 中 小]

这次说的是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

Java多线程从简单到复杂 http://www.linuxidc.com/Linux/2014-07/104435.htm

Java多线程经典案例 http://www.linuxidc.com/Linux/2014-06/103458.htm

Java多线程:ReentrantReadWriteLock读写锁的使用 http://www.linuxidc.com/Linux/2014-06/103457.htm

Java内存映射文件实现多线程下载 http://www.linuxidc.com/Linux/2014-05/102201.htm

Java多线程:一道阿里面试题的分析与应对 http://www.linuxidc.com/Linux/2014-03/98715.htm

Java中两种实现多线程方式的对比分析 http://www.linuxidc.com/Linux/2013-12/93690.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-09/106698.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款