當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Thread interrupt()用法及代碼示例

線程類的 interrupt() 方法用於中斷線程。如果任何線程處於睡眠或等待狀態(即調用 sleep() 或 wait()),則使用 interrupt() 方法,我們可以通過拋出 InterruptedException 來中斷線程執行。

如果線程未處於睡眠或等待狀態,則調用 interrupt() 方法執行正常行為,不會中斷線程,但會將中斷標誌設置為 true。

用法

public void interrupt()

返回

此方法不返回任何值。

異常

SecurityException:如果當前線程無法修改線程,則拋出此異常。

示例 1:中斷停止工作的線程

在這個程序中,中斷線程後,我們拋出一個新的異常,使其停止工作。

public class JavaInterruptExp1 extends Thread
{  
    public void run()
    {  
        try
        {  
            Thread.sleep(1000);  
            System.out.println("javatpoint");  
        }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("javatpoint");  
        }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() 方法隻將中斷標誌設置為真,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 Thread interrupt() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。