Java多線程 中斷機制及實例詳解
正文
這里詳細分析interrupt(),interrupted(),isInterrupted()三個方法
interrupt()
中斷這個線程,設(shè)置中斷標識位
public void interrupt() { if (this != Thread.currentThread()) checkAccess(); synchronized (blockerLock) { Interruptible b = blocker; if (b != null) { interrupt0(); // Just to set the interrupt flag b.interrupt(this); return; } } interrupt0(); }
我們來找下如何設(shè)置中斷標識位的
找到interrupt0()的源碼,src/hotspot/share/prims/jvm.cpp
JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread)) ... if (is_alive) { // jthread refers to a live JavaThread. Thread::interrupt(receiver); } JVM_END
調(diào)用了Thread::interrupt方法
src/hotspot/share/runtime/thread.cpp
void Thread::interrupt(Thread* thread) { ... os::interrupt(thread); }
os::interrupt方法,src/hotspot/os/posix/os_posix.cpp
void os::interrupt(Thread* thread) { ... OSThread* osthread = thread->osthread(); if (!osthread->interrupted()) { //設(shè)置中斷標識位 osthread->set_interrupted(true); ... } ... }
isInterrupted()
測試線程是否被中斷,線程的中斷狀態(tài)不會改變
public boolean isInterrupted() { return isInterrupted(false); }
查看native isInterrupted(boolean ClearInterrupted)源碼,查找方式同上
src/hotspot/os/posix/os_posix.cpp
bool os::is_interrupted(Thread* thread, bool clear_interrupted) { debug_only(Thread::check_for_dangling_thread_pointer(thread);) OSThread* osthread = thread->osthread(); // 查看是否被中斷 bool interrupted = osthread->interrupted(); // 清除標識位后再設(shè)置false if (interrupted && clear_interrupted) { osthread->set_interrupted(false); } return interrupted; }
Java傳遞ClearInterrupted為false,對應C++的clear_interrupted
interrupted()
測試線程是否被中斷,清除中斷標識位
public static boolean interrupted() { return currentThread().isInterrupted(true); }
簡單的例子
public class MyThread45 { public static void main(String[] args) throws Exception { Runnable runnable = new Runnable() { public void run() { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("線程被中斷了"); return ; } else { System.out.println("線程沒有被中斷"); } } } }; Thread t = new Thread(runnable); t.start(); Thread.sleep(500); t.interrupt(); System.out.println("線程中斷了,程序到這里了"); } }
檢查線程是否中斷,中斷線程,運行結(jié)果如下
······ 線程沒有被中斷 線程沒有被中斷 線程沒有被中斷 線程被中斷了 線程中斷了,程序到這里了
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于Spring自定義XML schema 擴展的問題(Spring面試高頻題)
今天給大家分享一道spring高頻率面試題關(guān)于Spring自定義XML schema 擴展的問題,今天以spring整合dubbo的實例給大家詳細講解下,感興趣的朋友跟隨小編一起看看吧2021-05-05SpringBoot實現(xiàn)excel文件生成和下載
這篇文章主要為大家詳細介紹了SpringBoot實現(xiàn)excel文件生成和下載,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-02-02java synchronized同步靜態(tài)方法和同步非靜態(tài)方法的異同
這篇文章主要介紹了java synchronized同步靜態(tài)方法和同步非靜態(tài)方法的異同的相關(guān)資料,需要的朋友可以參考下2017-01-01SpringBoot多線程與任務調(diào)度總結(jié)
多線程與任務調(diào)度是java開發(fā)中必須掌握的技能,本文主要介紹了SpringBoot多線程與任務調(diào)度總結(jié),具有一定的參考價值,感興趣的可以了解一下2023-12-12SpringBoot 2.0 整合sharding-jdbc中間件實現(xiàn)數(shù)據(jù)分庫分表
這篇文章主要介紹了SpringBoot 2.0 整合sharding-jdbc中間件,實現(xiàn)數(shù)據(jù)分庫分表,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-06-06