线程入门——加入一个线程

示例:this

/**
 * Created by Administrator on 2017/9/4.
 */

class Sleeper extends Thread {
    private int duration;

    public Sleeper(String name, int sleepTime) {
        super(name);
        duration = sleepTime;
        start();
    }

    public void run() {
        try {
            sleep(duration);
        } catch (InterruptedException e) {
            System.out.print(getName() + " was interrupted." + " isInterrupted():" + isInterrupted() + "\r\n");
            return;
        }
        System.out.print(getName() + " has awakened" + "\r\n");
    }
}

class Joiner extends Thread {
    private Sleeper sleeper;

    public Joiner(String name, Sleeper sleeper) {
        super(name);
        this.sleeper = sleeper;
        start();
    }

    public void run() {
        try {
            sleeper.join();
        } catch (InterruptedException e) {
            System.out.print("InterruptedException" + "\r\n");
        }
        System.out.print(getName() + " join completed" + "\r\n");
    }
}


public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("Sleepy", 1500);
        Sleeper grumpy = new Sleeper("Grumpy", 1500);

        Joiner dopey = new Joiner("Dopey", sleepy);
        Joiner doc = new Joiner("Doc", grumpy);
        grumpy.interrupt();
    }
}

 

一个线程能够在其余线程之上调用join()方法,其效果是等待一段时间直到第二个线程结束才能继续执行。若是某个线程在另外一个线程t上调用t.join(),此线程将被挂起,直到目标线程结束才能恢复(即t.isAlive()返回为假)也能够在调用join()时带上一个超时参数(单位能够是毫秒,或者毫秒和纳秒),这样若是目标线程在这段时间到期时尚未结束的话,join()方法总能返回。线程

对join()方法的调用能够被中断,作法是在调用线程上调用interrupt()方法,这时须要用到try-catch语句。对象

Sleeper是一个Thread类型,它要休眠一段时间。这段时间是经过构造器传进来的参数所指定的。在run()中,sleep()方法有可能在指定的时间期满时返回,但也可能被中断。在catch子句中,将根据isInterrupted()的返回值报告这个中断。当另外一个线程在该 线程上调用interrupt()时,将给该线程设定一个标志,代表该线程已经被中断。然而,异常被捕获时将清理这个标志,因此在catch子句中,在异常被捕获的时侯这个标志老是为假。除异常以外,这个标志还可用于其余状况,好比线程可能会检查其中断状态。get

Joiner线程将经过在Sleeper对象上调用Join()方法来等待sleeper原本。在main()里面,每一个Sleeper都有一个Joiner,能够在输出中发现,若是Sleeper被中断或者是正常结束,Joiner将和Sleeper一同结束。io

相关文章
相关标签/搜索