java需要关注的知识点---并发之加入一个新线程
程序员文章站
2022-03-23 14:52:20
...
package com.thread;
public class Joining {
public static void main(String[] args) {
Sleeper sleepy = new Sleeper("Sleepy",15000),
grumpy = new Sleeper("Grumpy",15000);
Joiner dopey = new Joiner("Dopey",sleepy),
doc = new Joiner("Doc",grumpy);
grumpy.interrupt();
}
}
class Sleeper extends Thread{
private int duration;
public Sleeper(String name,int duration) {
super(name);
this.duration = duration;
start();
}
public void run() {
try {
sleep(duration);
} catch (InterruptedException e) {
System.out.println(getName() + " is Interrupted:" + isInterrupted());
}
System.out.println(getName() + " has awakened");
}
}
class Joiner extends Thread{
private Sleeper sleeper;
public Joiner(String string, Sleeper sleepy) {
super(string);
this.sleeper = sleepy;
start();
}
public void run() {
try {
sleeper.join();
} catch (InterruptedException e) {
System.out.println(" is Interrupted:" + isInterrupted());
e.printStackTrace();
}
System.out.println(getName() + " join completed");
}
}