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類
下一篇:無