一 点睛
中断一个线程,意味着该线程在完成任务之前,停止它正在进行的一切当前的操作。
有三个比较常用的函数:
interrupt():一个正在运行的A线程,可以调用B线程对应的interrupt方法来中断线程B。这个方法的核心功能是,将线程B的中断标识位属性设置为true。
isInterrupted():通过该方法判断某个线程是否处于中断状态。
interrupted():这是一个静态方法,用来获取当前线程的中断状态,并清除中断状态。获取的是清除之前的值,也就是说连续两次调用此方法,第二次一定会返回false。
二 代码
public class SleepInterrupt implements Runnable
{
public void run()
{
try
{
System.out.println( “在run()方法中 ——这个线程休眠10秒” );
Thread.sleep( 10000 );
System.out.println( “在run()方法中 —— 继续运行” );
}
catch( InterruptedException x )
{
System.out.println( “在run()方法中 - 中断线程” );
return;
}
System.out.println( “在run()方法中 - 休眠之后继续完成” );
System.out.println( “在run()方法中 - 正常退出” );
}
public static void main( String[] args )
{
SleepInterrupt si = new SleepInterrupt();
Thread newThd = new Thread( si );
newThd.start();
// 在此休眠是为确保线程能运行一会
try
{
System.out.println( “在main()方法中——休眠2秒!” );
Thread.sleep( 2000 );
}
catch( InterruptedException e )
{
e.printStackTrace();
}
System.out.println( “在main()方法中——中断newThd 线程” );
newThd .interrupt();
System.out.println( “在main()方法中 ——退出” );
}
}
三 运行
在main()方法中——休眠2秒!
在run()方法中 ——这个线程休眠10秒
在main()方法中——中断newThd 线程
在run()方法中 - 中断线程
在main()方法中 ——退出
四 说明
interrupt()方法并不会使正在执行的线程停止执行,它只对wait、join、sleep等方法或由于I/O操作等原因受阻的线程产生影响,使其退出暂停执行的状态。
它对正在运行的线程不起作用。
原文链接:https://blog.csdn.net/chengqiuming/article/details/95716512