加入一个线程

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.println(getName() + "was interrupted." + "isInterrupted():" + isInterrupted());
        }
        System.out.println(getName()+"has awakened");
 }
}
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.println("Interrupted");
        }
        System.out.println(getName()+"join completed");
    }
}
public class Joining {
    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);
        grumpy.interrupt();
 }
}
  • 如果某个线程执行过程中,用t.join()调用另一个执行的线程t,那么此线程将被挂起,知道t结束才恢复
  • 可以在调用join()时带上一个参数,如果目标线程在这段时间没有结束的话,join方法总能返回
  • join()方法也可以被中断,在被调用的线程上调用interrupt()方法
  • 调用Interrupt()方法,给线程设置一个标记来表示已中断。但是在Interrupt被捕获时,这个标记被清除,isInterrupt总为false

贤魚
20 声望1 粉丝

如露亦如电


« 上一篇
Java 线程(二)
下一篇 »
Java I/O系统