线程中断

java提供了线程中断机制,可以利用线程中断机制来结束线程,运行过程中检查线程是否被中断或者捕获InterruptedException异常。
判断中断的两种方式:
Thread.interrupted(); 可以设置中断的值为false
isInterrupted()

检查中断:

public class Demo5 {

public static void main(String[] args) {
ThreadD threadD = new ThreadD();
threadD.start();
try {
Thread.sleep(3000);
threadD.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}

}

static class ThreadD extends Thread{

public ThreadD() {
super();
}

@Override
public void run() {
while (true) {
if (isInterrupted()) {
System.out.println("=========退出============");
return ;
}else {
System.out.println("=========run============");
}
}
}
}
}
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
利用捕获中断停止线程:

public class Demo5 {

public static void main(String[] args) {
ThreadE threadE = new ThreadE();
threadE.start();
try {
Thread.sleep(3000);
threadE.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}

}

static class ThreadE extends Thread {

public ThreadE() {
super();
}

@Override
public void run() {
try {
test1();
} catch (InterruptedException e) {
e.printStackTrace(http://www.amjmh.com/v/BIBRGZ_558768/);
}
}

private void test1() throws InterruptedException {
while (true) {
if (!isInterrupted()) {
System.out.println("=========run============");
} else {
throw new InterruptedException();
}
}

}

}
}

posted @ 2019-09-12 17:28  李艳艳665  阅读(111)  评论(0编辑  收藏  举报