欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java多線(xiàn)程 中斷機(jī)制及實(shí)例詳解

 更新時(shí)間:2019年09月06日 08:21:51   作者:慢慢來(lái)  
這篇文章主要介紹了Java多線(xiàn)程 中斷機(jī)制及實(shí)例詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

正文

這里詳細(xì)分析interrupt(),interrupted(),isInterrupted()三個(gè)方法

interrupt()

中斷這個(gè)線(xiàn)程,設(shè)置中斷標(biāo)識(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();
  }

我們來(lái)找下如何設(shè)置中斷標(biāo)識(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è)置中斷標(biāo)識(shí)位
  osthread->set_interrupted(true);
  ...
 }
  ...
}

isInterrupted()

測(cè)試線(xiàn)程是否被中斷,線(xiàn)程的中斷狀態(tài)不會(huì)改變

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();
 // 清除標(biāo)識(shí)位后再設(shè)置false
 if (interrupted && clear_interrupted) {
  osthread->set_interrupted(false);
 }
 return interrupted;
}

Java傳遞ClearInterrupted為false,對(duì)應(yīng)C++的clear_interrupted

interrupted()

測(cè)試線(xiàn)程是否被中斷,清除中斷標(biāo)識(shí)位

  public static boolean interrupted() {
    return currentThread().isInterrupted(true);
  }

簡(jiǎn)單的例子

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("線(xiàn)程被中斷了");
            return ;
          }
          else
          {
            System.out.println("線(xiàn)程沒(méi)有被中斷");
          }
        }
      }
    };
    Thread t = new Thread(runnable);
    t.start();
    Thread.sleep(500);
    t.interrupt();
    System.out.println("線(xiàn)程中斷了,程序到這里了");
  }
}

檢查線(xiàn)程是否中斷,中斷線(xiàn)程,運(yùn)行結(jié)果如下

······
線(xiàn)程沒(méi)有被中斷
線(xiàn)程沒(méi)有被中斷
線(xiàn)程沒(méi)有被中斷
線(xiàn)程被中斷了
線(xiàn)程中斷了,程序到這里了

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論