java 结束线程退出系统Systemexit0退出方法
在Java中,可以通过调用Thread类的interrupt()方法来结束一个线程的执行。当线程被中断后,可以在线程的run()方法中检查线程的中断状态,然后进行相应的处理,最终退出线程。
以下是一个示例代码:
public class MyThread extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 线程的执行逻辑
// 检查线程的中断状态
if (Thread.currentThread().isInterrupted()) {
break; // 退出循环,结束线程
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
// 在需要结束线程的地方调用 thread.interrupt() 方法
thread.interrupt();
// 等待线程执行完毕
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 退出系统
System.exit(0);
}
}
在上述代码中,通过调用thread.interrupt()方法来中断线程的执行。然后,在MyThread类的run()方法中检查线程的中断状态,如果线程被中断,就退出循环,结束线程的执行。
最后,使用System.exit(0)来退出系统。参数0表示正常退出,非0表示异常退出
原文地址: https://www.cveoy.top/t/topic/iwt2 著作权归作者所有。请勿转载和采集!