Java并发 | 12.[方法] interrupt( )打断
文章目录
- 1. t1.interrupt( ) - 打断线程
- 2. t1.isInterrupted( ) - 获取打断标记
- 2.1. 获取其他线程的打断标记
- 2.2. 获取本线程的打断标记
- 3. 示例代码
1. t1.interrupt( ) - 打断线程
执行该方法后,会根据 t1 当前正处的状态执行不同的操作:
- 若 t1 正处于 Waiting 或 Timed Waiting 状态,t1线程会抛出 InterruptedException,并且 会将打断标记重置为false;
- 若 t1 正处于 Runnable 状态,t1会照常运行,仅仅只是 将打断标记设置为true。
2. t1.isInterrupted( ) - 获取打断标记
2.1. 获取其他线程的打断标记
如果希望在 main 线程中获取 t1 的打断标记,直接调用 t1.isInterrupted( ) 即可:
t1.isInterrupted(); // true 或 false
2.2. 获取本线程的打断标记
如果希望获取本线程的打断标记,则需要先通过 Thread.currentThread( ) 获取当前线程对应的对象:
Thread t1 = new Thread(()-> {
// 获取当前线程对象
Thread curThread = Thread.currentThread();
// 输出打断标记
System.out.println(curThread.isInterrupted());
});