-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJoinTest.java
More file actions
62 lines (56 loc) · 1.43 KB
/
JoinTest.java
File metadata and controls
62 lines (56 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package Thread.Basic;
public class JoinTest {
public static void main(String[] args) {
Sleep sleep=new Sleep("sleep", 3000);
Joiner joiner=new Joiner(sleep, "Joiner");
joiner.start();
//对join的方法可以被中断,调用Interrupt方法
sleep.interrupt();
}
}
class Sleep extends Thread{
private int duration;
public Sleep(String name,int dutation){
//调用父类的Thread(String name)的构造函数
super(name);
this.duration=dutation;
start();
}
public void run() {
try {
sleep(duration);
} catch (InterruptedException e) {
//这里显示没有被中断,,原因:在调用isInterrupt时,会被设置一个中断标志位,但是捕获异常时会清除这个标志
System.out.println(this.getName()+"被阻塞"+duration+"毫秒"+"目前是否被中断:"+isInterrupted());
//return ;
}
System.out.println(getName()+"线程has awakened");
}
}
class Joiner extends Thread{
private Sleep sleep;
private int count=5;
public Joiner(Sleep sleep,String name){
this.sleep=sleep;
}
@Override
public void run() {
while(true){
System.out.println(this);
if(count--==0)
return;
if(count==3){
try {
sleep.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(getName()+"is Interrupted");
}
System.out.println(getName()+"join 完成");
}
}
}
public String toString(){
return getName()+":"+count;
}
}