在Java中,正确中断线程通常有两种方法: 使用interrupt()方法:调用线程对象的interrupt()方法可以中断线程
在Java中,正确中断线程通常有两种方法:
- 使用interrupt()方法:调用线程对象的interrupt()方法可以中断线程。当线程被中断时,会设置线程的中断标志位为true,并抛出InterruptedException异常。在线程执行过程中,可以通过检查中断标志位来决定是否继续执行或者停止线程。
示例代码如下:
Threadthread=newThread(()->{
while(!Thread.currentThread().isInterrupted()){
//执行线程逻辑
}
});
thread.start();
//中断线程
thread.interrupt();
示例代码如下:
volatilebooleanflag=true;
Threadthread=newThread(()->{
while(flag){
//执行线程逻辑
}
});
thread.start();
//中断线程
flag=false;
需要注意的是,中断线程并不意味着线程立即停止,而是设置了中断标志位之后,线程可以根据中断标志位来决定是否停止执行。在编写线程逻辑时,需要在适当的地方检查中断标志位,以确保线程可以正确响应中断。
版权声明
本文仅代表作者观点,不代表博信信息网立场。