Java interrupt()方法
线程类的
interrupt()方法用于中断线程。如果任何线程处于睡眠或等待状态(即调用sleep()或wait()),则使用interrupt()方法,我们可以通过抛出InterruptedException来中断线程的执行。
如果线程未处于睡眠或等待状态,则调用interrupt()方法将执行正常行为,并且不会中断线程,而是将中断标志设置为true。
语法
返回
此方法不返回任何值。
异常
安全性异常: 如果当前线程无法修改该线程,则会引发此异常。
示例1: 中断一个停止工作的线程
在此程序中,中断后线程,我们抛出一个新异常,因此它将停止工作。
public class JavaInterruptExp1 extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("lidihuo");
}
catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void main(String args[])
{
JavaInterruptExp1 t1=new JavaInterruptExp1();
t1.start();
try
{
t1.interrupt();
}
catch(Exception e){
System.out.println("Exception handled "+e);
}
}
}
输出:
Exception in thread "Thread-0" java.lang.RuntimeException: Thread interrupted...java.lang.InterruptedException: sleep interrupted
at JavaInterruptExp1.run(JavaInterruptExp1.java:10)
示例2: 中断一个不会停止工作的线程
在此示例中,我们在中断线程之后处理了异常,因此它将从休眠中爆发状态,但不会停止工作。
public class JavaInterruptExp2 extends Thread
{
public void run()
{
try
{
//Here current threads goes to sleeping state
// Another thread gets the chance to execute
Thread.sleep(500);
System.out.println("lidihuo");
}
catch(InterruptedException e){
System.out.println("Exception handled "+e);
}
System.out.println("thread is running...");
}
public static void main(String args[])
{
JavaInterruptExp2 t1=new JavaInterruptExp2();
JavaInterruptExp2 t2=new JavaInterruptExp2();
// call run() method
t1.start();
// interrupt the thread
t1.interrupt();
}
}
输出:
Exception handled java.lang.InterruptedException: sleep interrupted
thread is running...
示例3: 中断正常运行的线程
在此程序中,线程执行期间没有发生异常。在这里,interrupt()方法仅将interrupted标志设置为true,以后Java程序员可以使用该标志来停止线程。
public class JavaInterruptExp3 extends Thread
{
public void run()
{
for(int i=1; i<=5; i++)
System.out.println(i);
}
public static void main(String args[])
{
JavaInterruptExp3 t1=new JavaInterruptExp3();
// call run() method
t1.start();
t1.interrupt();
}
}
输出: