多线程join

多线程 join

举个例子:A线程中调用B线程,A线程中的业务需要等待B线程执行完成后才可继续执行。那么A线程的代码中调用B线程的join方法实现这一目的(总结:等待被调用的线程执行完成后,自己再接着执行)

不带时间参数的join

public class Demo implements Runnable{
    @Override
    public void run() {
      try {
        // 每睡眠1s,输出一次,一共执行5次
        for (int i = 0; i < 5; i++) {
          TimeUnit.SECONDS.sleep(1);
          System.out.println(Thread.currentThread().getName()+i);
        }
      } catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
    }
}

Main

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Demo demo = new Demo();
        Thread a = new Thread(demo, "thread a_");
        a.start();
        a.join();//主线程中调用线程a的join,等待线程a执行完毕后再继续执行
        System.out.println("over");
    }
}

打印结果

thread a_0
thread a_1
thread a_2
thread a_3
thread a_4
over

如果不使用join,看看打印结果

over
thread a_0
thread a_1
thread a_2
thread a_3
thread a_4

很显然,没有使用join 时,主线程完全不会等待线程a执行完毕再继续执行,而是启了线程a后,接着往下执行自己的代码了。

使用了join主线程 在调用了线程ajoin方法后,处于阻塞状态,一旦线程a执行完毕或者超时时间结束,主线程就会从阻塞状态(Block state)变为就绪状态(Runnable state),等待CPU调度执行。

带时间参数的join

带时间参数的join方法,代表等待的时长(毫秒级),也可以理解为阻塞的时长,就是主线程停止不继续执行的时长,超时后,主线程 继续往下执行。继续上述例子

Main

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Demo demo = new Demo();
        Thread a = new Thread(demo, "thread a_");
        a.start();
        a.join(2100);//主线程中调用线程a的join,等待2.1s后继续执行
        System.out.println("over");
    }
}

打印结果

thread a_0
thread a_1
over # 因为线程a每隔1s输出一次,主线程等待2.1s,所以线程a输出两次后,主线程继续执行
thread a_2
thread a_3
thread a_4
posted @ 2024-05-08 23:00  勤匠  阅读(20)  评论(0)    收藏  举报