打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
线程 Join方法:将某个子线程合并到主线程,即等子线程全部运行全部执行完之后才执行主线程...
线程 Join方法:将某个子线程合并到主线程,即等子线程全部运行全部执行完之后才执行主线程
2011-03-17 11:49

Join 方法:将某个子线程合并到主线程,即等子线程全部运行全部执行完之后才执行主线程.

例1 (不调用join,主线程与子线程同时运行)

-----

package com.wlh;

public class TestJoin {
  public static void main(String[] args) {
    MyThread2 t1 = new MyThread2("子线程");
    t1.start();
     /*    try {
     t1.join();
    } catch (InterruptedException e) {}*/
     
    for(int i=1;i<=10;i++){
     try {
   Thread.sleep(1000);//当前线程休息1000秒
   System.out.println("i am main thread");
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
     
    }
  }
}
class MyThread2 extends Thread {
  MyThread2(String s){
   super(s);
  }
 
  public void run(){
    for(int i =1;i<=10;i++){
      System.out.println("i am "+getName());
      try {
       sleep(1000);//当前线程休息1000秒
      } catch (InterruptedException e) {
       return;
      }
    }
  }
}

--------------------------------------------------------------

输出:

备注:子线程和主线程交替执行 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 
i am 子线程 
i am main thread 

-----------------------------------------------------------------

 

** 例子2 (调用 join 方法)

在 t1.start()子线程就绪;之后添加t1.join(),则等t1线程执行完之后才执行主线程 

---------------

package com.wlh;

public class TestJoin {
  public static void main(String[] args) {
    MyThread2 t1 = new MyThread2("子线程");
    t1.start();
      try {
     t1.join();
    } catch (InterruptedException e) {}     
    for(int i=1;i<=10;i++){
     try {
   Thread.sleep(1000);//当前线程休息1000秒
   System.out.println("i am main thread");
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
     
    }
  }
}
class MyThread2 extends Thread {
  MyThread2(String s){
   super(s);
  }
 
  public void run(){
    for(int i =1;i<=10;i++){
      System.out.println("i am "+getName());
      try {
       sleep(1000);//当前线程休息1000秒
      } catch (InterruptedException e) {
       return;
      }
    }
  }
}

--------------------

输出结果: 


i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am 子线程 
i am main thread 
i am main thread 
i am main thread 
i am main thread 
i am main thread 
i am main thread 
i am main thread 
i am main thread 
i am main thread 
i am main thread 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java多线程run()和start()
java基本教程之join方法详解 java多线程教程
采用Thread.join()或CountDownLatch来实现线程间同步
Java多线程(2):线程加入/join()
Java主线程等待子线程、线程池
Java主线程等待所有子线程执行完毕再执行解决办法集
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服