Java代码中如何中断线程呢?
下文笔者讲述使用Java代码中断线程的方法分享,如下所示:
实现思路:
使用interrupt()方法进行线程中断
在中断前,我们可使用isInterrupted()方法,判断一下线程是否已中断
例:
package com.java265.other;
public class Test16 {
public static void main(String[] args) throws Exception {
MyThread2 a = new MyThread2();
// 启动线程
a.start();
try {
Thread.sleep(2000);
} catch (InterruptedException x) {
}
System.out.println("in main() - 中断其他线程");
a.interrupt();
System.out.println("in main() - 离开");
}
}
class MyThread2 extends Thread {
public void run() {
try {
System.out.println("in run() - 将运行 work() 方法");
work();
System.out.println("in run() - 从 work() 方法回来");
} catch (InterruptedException x) {
System.out.println("in run() - 中断 work() 方法");
return;
}
System.out.println("in run() - 休眠后执行");
System.out.println("in run() - 正常离开");
}
public void work() throws InterruptedException {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
Thread.sleep(2000);
System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
}
}
}
}
-----运行以上代码,将输出以下信息-----
in run() - 将运行 work() 方法
in main() - 中断其他线程
in main() - 离开
C isInterrupted()=true
in run() - 中断 work() 方法
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


