package com.dq;
public class ThreadTest {
public static void main(String[] args) {
Runnable task = new Task();
Thread thread = new Thread(task);
thread.start();
try
{
Thread.sleep(100);
thread.interrupt();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
thread.interrupt();
}
}
class Task implements Runnable {
@Override
public void run() {
while(true)
{
if(Thread.currentThread().isInterrupted())
{
return;
}
try
{
for(int index = 0; index < 100; index++)
{
System.out.println("线程进行中");
}
Thread.sleep(1000);
}
catch (InterruptedException e)
{
System.out.println("线程睡眠中被中断,返回了");
// 下面这一句是精华所在,如果不加上这一句线程永远也停不下来,线程内捕获到异常时线程的停止
//标志位会被清除,此时Thread.currentThread().isInterrupted()会返回false,因此需要再
//次手动发送以下的信号,这样Thread.currentThread().isInterrupted()就会返回true了,
//主要是明确原理
Thread.currentThread().interrupt();
}
}
}
}
线程方法中有异常时线程的停止
最新推荐文章于 2022-12-18 14:45:39 发布