共計 756 個字符,預計需要花費 2 分鐘才能閱讀完成。
Java 中的 interrupt()
方法用于中斷一個線程的執行。使用 interrupt()
方法會設置線程的中斷狀態為true
,但是并不會立即停止線程的執行,而是根據具體情況來決定是否中斷線程的執行。
下面是使用 interrupt()
方法的一般步驟:
- 創建一個線程對象,并實現
Runnable
接口或是繼承Thread
類,在run()
方法中編寫需要執行的代碼。 - 在需要中斷線程的地方調用線程對象的
interrupt()
方法。 - 在線程的執行代碼中,使用
Thread.interrupted()
或是Thread.currentThread().isInterrupted()
來判斷線程的中斷狀態,并根據中斷狀態來決定是否終止線程的執行。
下面是一個簡單的示例:
public class MyThread implements Runnable {public void run() {// 執行一些循環操作
while (!Thread.currentThread().isInterrupted()) {// 線程的具體執行代碼
// ...
}
}
public static void main(String[] args) {Thread thread = new Thread(new MyThread());
thread.start();
// 中斷線程的執行
thread.interrupt();}
}
在上面的示例中,MyThread
類實現了 Runnable
接口,并在 run()
方法中執行了一些循環操作。在循環中通過 Thread.currentThread().isInterrupted()
來判斷線程的中斷狀態,如果中斷狀態為true
,則退出循環,終止線程的執行。
在 main()
方法中,通過 thread.interrupt()
來中斷線程的執行。
丸趣 TV 網 – 提供最優質的資源集合!
正文完