Thread
类的interrupt()
方法用于中断线程。如果任何线程处于休眠或等待状态(即调用sleep()
或wait()
),那么使用interrupt()
方法,可以通过抛出InterruptedException
来中断线程执行。
如果线程未处于休眠或等待状态,则调用interrupt()
方法将执行正常行为,并且不会中断线程,但会将中断标志设置为true
。
语法
public void interrupt()
异常
SecurityException
:如果当前线程无法修改线程,则抛出此异常。
示例一 :中断停止工作的线程
在这个程序中,在中断线程之后,抛出一个新的异常,因此它将停止工作。
public class JavaInterruptExp1 extends Thread
{
public void run()
{
try
{
Thread.sleep(1000);
System.out.println("zaixian");
}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)
示例二 :中断不停止工作的线程
在这个例子中,在中断线程之后,处理异常,因此它将从休眠状态中突破但不会停止工作。
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("zaixian");
}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...
示例三 :中断行为正常的线程
在此程序中,线程执行期间没有发生异常。 这里,interrupt()
方法仅将中断标志设置为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();
}
}
执行上面示例代码,得到以下结果:
1
2
3
4
5
上一篇:
Java Runtime类
下一篇:无