Thread
類的interrupted()
方法用於檢查當前執行緒是否已被中斷。 此方法清除執行緒的中斷狀態,這意味著如果要連續兩次呼叫此方法,則第二次呼叫將返回false
。 如果執行緒的中斷狀態為true
,則此方法將狀態設定為false
。
語法
public static boolean interrupted()
返回
如果當前執行緒已被中斷,則此方法將返回true
,否則返回false
。
範例
public class JavaInterruptedExp extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println("doing task....: "+i);
}
}
public static void main(String args[])throws InterruptedException
{
JavaInterruptedExp t1=new JavaInterruptedExp();
JavaInterruptedExp t2=new JavaInterruptedExp();
// call run() method
t1.start();
t2.start();
System.out.println("is thread t1 interrupted..: "+t1.interrupted());
// interrupt thread t1
t1.interrupt();
System.out.println("is thread t1 interrupted..: " +t1.interrupted());
System.out.println("is thread t2 interrupted..: "+t2.interrupted());
}
}
執行上面範例程式碼,得到以下結果:
is thread t1 interrupted..: false
is thread t1 interrupted..: false
is thread t2 interrupted..: false
doing task....: 1
doing task....: 2
doing task....: 3
doing task....: 1
doing task....: 2
doing task....: 3