Java中线程的状态以及状态的转化
- NEW 创建线程
- TIMED_WAITING 线程无限等待或者超时等待
- WATING 线程等待
- RUNNABLE 线程处于运行态(RUNNING)或者就绪态(READY)
- TERMINATED 终止
- BLOCKED 锁 线程阻塞
线程中对于线程中断方法API的应用
-
静态方法 static boolean interrupt() 测试当前线程是否中断 静态方法 就是作用于在当前代码行,作用于当前代码行的线程。
这个方法获取了前线程的中断标志位但是会重置中断标志位
package Lesson2; public class InterruptedTest2 { public static void main(String[] args) { Thread t = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { // Thread.interrupted() 返回当前线程的中断标志位,然后重置中断标志位 System.out.println(i + " " + Thread.interrupted()); } } }); t.start(); System.out.println("main.start"); t.interrupt(); // 将t线程中断标志位设置为 true System.out.println("main.end"); } }
其中之一的结果就是
t.start t.end 0 true 1 false 2 false 3 false 4 false 5 false1 7 false 8 false 9 false
由此我们可以得出,当我们使用了这个静态方法获取了当前线程的中断标志位之后,这个静态方法就会重置线程的标志位将它设置位false。
-
实例方法 void interrupt() 中断这个线程;boolean isInterrupted() 测试这个线程是否被中断。 实例方法 作用于调用的线程上
对线程调用使用 void interrupt() ,我们就会将线程的中断标志位设置位true,告诉这个线程要让他中断,然后由线程的内部的run()方法自己去决定是否要中断。 当我们interrupt() 的时候,即使当前线程处于阻塞状态,也会以抛异常的方式中断这个线程。但是当线程中以抛出InterruptedException的方式的时候 也会重置t线程的标志位。
boolean isInterrupted() 这个线程并不会重置标志位
package Lesson2;
/**
* 使用 interrupt()之后 代码决定线程是否结束
* */
public class MyInterruptedTest {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000 && !Thread.currentThread().isInterrupted() ;i++) {
System.out.println(i);
}
}
});
t.start();
System.out.println("xxx");
Thread.sleep(1);
t.interrupt();
System.out.println("yyy");
}
}
结果
xxx
0
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
yyy
Process finished with exit code 0
这两个方法一般都是相互配合使用。
package Lesson2;
/**
* 使用 interrupt()之后 代码决定线程是否结束
* */
public class MyInterruptedTest {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100000 && !Thread.currentThread().isInterrupted() ;i++) {
System.out.println(i);
try {
Thread.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
System.out.println("xxx");
Thread.sleep(1);
t.interrupt();
System.out.println("yyy");
}
}
结果
xxx
0
yyy
1
2
3
4
5
6
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at Lesson2.MyInterruptedTest$1.run(MyInterruptedTest.java:18)
at java.lang.Thread.run(Thread.java:748)
7
8
9
10
11
12
13
14
15
16
接下来会输出完