Thread.join详解

/**
 * 如果某个线程在另一个线程t上调用t.join;那么此线程将被挂起,直到目标t线程的结束才恢复即t.isAlive返回为假
 * 
 * @date:2018年6月27日
 * @author:zhangfs
 * 
 * 
 */
public class ClientDemo {

    public static void main(String[] args) {
        SleepThread sleepThread1 = new SleepThread("sleepThread1", 1500),
                sleepThread2 = new SleepThread("sleepThread2", 1500);

        JoinThread joinThread1 = new JoinThread("joinThread1", sleepThread1),
                joinThread2 = new JoinThread("joinThread2", sleepThread2);

        sleepThread2.interrupt();

    }
}
 
   

public class SleepThread extends Thread {

 
   

private int duration;

 
   

 

 
   

public SleepThread(String name, int sleepTime) {

 
   

super(name);

 
   

this.duration = sleepTime;

 
   

start();

 
   

}

 
   

 

 
   

@Override

 
   

public void run() {

 
   

// TODO Auto-generated method stub

 
   

// super.run();

 
   

try {

 
   

sleep(duration);

 
   

} catch (InterruptedException e) {

 
   

// TODO Auto-generated catch block

 
   

// e.printStackTrace();

 
   

System.out.println(getName() + " was interrupted. is interrupted is :" + isInterrupted());

 
   

return;

 
   

}

 
   

System.out.println(getName() + " has awakened");

 
   

}

 
   

}

 

 

public class JoinThread extends Thread {

 

private SleepThread sleepThread;

 

public JoinThread(String name, SleepThread sleepThread) {

super(name);

this.sleepThread = sleepThread;

start();

}

 

@Override

public void run() {

// TODO Auto-generated method stub

try {

sleepThread.join();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

// e.printStackTrace();

System.out.println("interrupted ");

}

System.out.println(getName() + "  Join Complete");

}

}


output:
 
 

sleepThread2 was interrupted. is interrupted is :false

 
 

joinThread2  Join Complete

 
 

sleepThread1 has awakened

 
 

joinThread1  Join Complete

 

猜你喜欢

转载自www.cnblogs.com/zhangfengshi/p/9234953.html