Java多线程join()

来源:互联网 发布:java 变量类型 编辑:程序博客网 时间:2024/06/01 19:04

thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
也可以在调用join()时带上一个超时的参数,这样如果目标线程A在这段时间到期时还没有结束的话,join()方法返回,执行线程B,这个时候AB两个线程一起执行。 并且对join()方法的调用可以被中断,做法是在调用线程上调用interrupt()方法。

public class Sleeper extends Thread {    private int duration;    public Sleeper(String name,int sleepTime){        super(name);        duration = sleepTime;        start();    }    @Override    public void run() {        try {            sleep(duration);        } catch (Exception e) {            System.out.println(getName() + "被中断。" + "isInterrupted():" + isInterrupted());        }        System.out.println(getName() + "已唤醒。");    }}

这里写图片描述

public class Joiner extends Thread {    private Sleeper sleeper;    public Joiner(String name,Sleeper sleeper){        super(name);        this.sleeper = sleeper;        start();    }    @Override    public void run() {        try {            sleeper.join();        } catch (Exception e) {            // TODO: handle exception        }        System.out.println(getName() + "加入完成。");    }    public static void main(String[] args) {        Sleeper sleepy = new Sleeper("Sleepy", 1500),                grumpy = new Sleeper("Grumpy", 1500);        Joiner dopey = new Joiner("Dopey", sleepy),               doc = new Joiner("Doc", grumpy);        sleepy.interrupt();    }}

这里写图片描述

join()使用意义:

主线程B生成并起动了子线程A,而子线程A里要进行大量的耗时的运算,当主线程B处理完其他的事务后,需要用到子线程A的处理结果,这个时候就要用到join()方法了。

0 0
原创粉丝点击