你的位置:首页 > Java教程

[Java教程][javaSE] 多线程(join方法)


多条线程并发执行,随机切换,调用join()方法,会使当前线程所在的线程(一般主线程)冻结,直到当前线程结束,所在的线程才恢复继续执行

 

class JoinTestDemo implements Runnable{  @Override  public void run() {        for(int x=0;x<=5;x++){      try {        Thread.sleep(100);      } catch (InterruptedException e) {        // TODO Auto-generated catch block        e.printStackTrace();      }      System.out.println(Thread.currentThread().getName()+"===="+x);    }  }  }public class JoinDemo {  /**   * @param args   * @throws InterruptedException   */  public static void main(String[] args) throws InterruptedException {    JoinTestDemo join=new JoinTestDemo();    Thread t1=new Thread(join);    Thread t2=new Thread(join);    t1.start();    t2.start();    //上面两个子线程交替执行,主线程冻结,t1走完才解冻    t1.join();    //显示主线程    for(int x=0;x<=5;x++){      Thread.sleep(100);      System.out.println(Thread.currentThread().getName()+"===="+x);    }  }}