中斷執行緒 interrupt

2021-10-04 02:29:53 字數 1480 閱讀 2148

呼叫interrupt(),通知執行緒應該中斷:

1 如果執行緒處於阻塞狀態,則執行緒立即退出被阻塞狀態,並丟擲乙個interruptedexception異常;

2 如果執行緒處於正常活動狀態,那

package com.mall.controllor.alene;

import sun.management.snmp.jvminstr.jvmthreadinstanceentryimpl;

/** * created by 60341 on 2020/3/18.

*/public class interruptdemo

} catch (interruptedexception e) }};

thread t1 = new thread(interrupttask,"t1");

system.out.println(t1.getname()+" "+ t1.getstate() + " is new");

t1.start();

system.out.println(t1.getname()+" "+ t1.getstate() + " is started");

//主線程休眠300ms,主線程給t1發中斷指令;

thread.sleep(300);

//t1執行緒收到中斷命令,isinterrupted()置為false,while(!thread.currentthread().isinterrupted())立刻被檢測到,如果在阻塞狀態,則丟擲異常被catch處理。如果是正常執行,只將阻塞標誌置為true,執行緒繼續進行,不影響下面操作。

t1.interrupt();

system.out.println(t1.getname()+" "+ t1.getstate() + " is interrupted");

//主線程休眠300ms,檢視t1狀態;

thread.sleep(300);

system.out.println(t1.getname()+" "+ t1.getstate() + " is interrupted now");

}/*輸出:

t1 new is new

t1 runnable is started

currentthread name is t1;currentthread status is runnable loop 1

currentthread name is t1;currentthread status is runnable loop 2

t1 timed_waiting is interrupted

currentthread name is t1;currentthread status is runnablecatch interruptedexception

t1 terminated is interrupted now

*/}

麼該執行緒的中斷標誌設為true,被設定中斷標誌的執行緒將繼續正常執行,不受影響。

執行緒中斷interrupt

案例 這裡需要注意一下,try catch到interruptedexception e異常時,中斷訊號會被抹除,所以th.isinterrupted 如果執行在catch異常前,則isinterrupted為true,可以正常退出,否則中斷訊號抹除後,isinterrupted得到的值為false...

雜談 執行緒中斷 Interrupt

以前有乙個錯誤的認識,以為中斷操作都會丟擲異常,後來才發現並不是這樣,所以今天就來做乙個關於中斷的總結。已被棄用的stop方法 早期,thread類中有乙個stop方法,用於強行關閉乙個執行緒。但是後來發現此操作並不安全,強行關閉可能導致一致性問題。故stop方法已被官方棄用。具體原因請看why a...

Java 多執行緒 interrupt 中斷

當乙個執行緒執行時,另乙個執行緒可以呼叫對應的thread物件的interrupt 方法來中斷它,該方法只是在目標執行緒中設定乙個標誌,表示它已經被中斷,並立即返回。這裡需要注意的是,如果只是單純的呼叫interrupt 方法,執行緒並沒有實際被中斷,會繼續往下執行。created by yangt...