Java多線程(十二):中斷機制

這裏詳細分析interrupt(),interrupted(),isInterrupted()三個方法java

interrupt()

中斷這個線程,設置中斷標識位c++

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();
    }

咱們來找下如何設置中斷標識位的
找到interrupt0()的源碼,src/hotspot/share/prims/jvm.cppjvm

JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
  ...
  if (is_alive) {
    // jthread refers to a live JavaThread.
    Thread::interrupt(receiver);
  }
JVM_END

調用了Thread::interrupt方法
src/hotspot/share/runtime/thread.cpp測試

void Thread::interrupt(Thread* thread) {
  ...
  os::interrupt(thread);
}

os::interrupt方法,src/hotspot/os/posix/os_posix.cppthis

void os::interrupt(Thread* thread) {
  ...
  OSThread* osthread = thread->osthread();
  if (!osthread->interrupted()) {
    //設置中斷標識位
    osthread->set_interrupted(true);
    ...
  }
    ...
}

isInterrupted()

測試線程是否被中斷,線程的中斷狀態不會改變線程

public boolean isInterrupted() {
        return isInterrupted(false);
    }

查看native isInterrupted(boolean ClearInterrupted)源碼,查找方式同上
src/hotspot/os/posix/os_posix.cppdebug

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();

  // 清除標識位後再設置false
  if (interrupted && clear_interrupted) {
    osthread->set_interrupted(false);
  }

  return interrupted;
}

Java傳遞ClearInterrupted爲false,對應C++的clear_interruptedcode

interrupted()

測試線程是否被中斷,清除中斷標識位源碼

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

簡單的例子io

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("線程中斷了,程序到這裏了");
    }
}

檢查線程是否中斷,中斷線程,運行結果以下

······
線程沒有被中斷
線程沒有被中斷
線程沒有被中斷
線程被中斷了
線程中斷了,程序到這裏了
相關文章
相關標籤/搜索