java学习-并发-interrupted
/* Interrupt state of the thread - read/written directly by JVM */ private volatile boolean interrupted;
根据Thread#interrupted可以了解到,interrupted 实际 是线程中止状态,而对于当前字段真实状态是由jvm c++ 代码进行操作的; 且使用volatile保证了其可见性;
public void interrupt() { if (this != Thread.currentThread()) { checkAccess(); // thread may be blocked in an I/O operation synchronized (blockerLock) { Interruptible b = blocker; if (b != null) { interrupted = true; interrupt0(); // inform VM of interrupt b.interrupt(this); return; } } } interrupted = true; // inform VM of interrupt interrupt0(); // 这里是调用的native方法 }
对于interrupt0 native 映射 在 thread.c 中 存在 映射定义 "{"interrupt0", "()V", (void *)&JVM_Interrupt},"
可以看到在 jvm.cpp 中存在 真正执行的代码为
openjdk 15 source - jvm.cpp
JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread)) JVMWrapper("JVM_Interrupt"); ThreadsListHandle tlh(thread); JavaThread* receiver = NULL; bool is_alive = tlh.cv_internal_thread_to_JavaThread(jthread, &receiver, NULL); if (is_alive) { // 首先会判读当前java object(jthread) 中关联的 JavaThread(c++ 对象) 是否存活,JavaThread的存活表示 os线程的存活 // jthread refers to a live JavaThread. receiver->interrupt(); // 此时调用 JavaThread::interrupt方法 } JVM_END
openjdk 15 source - thread.cpp
// interrupt support void JavaThread::interrupt() { debug_only(check_for_dangling_thread_pointer(this);) // For Windows _interrupt_event osthread()->set_interrupted(true); // 修改线程的状态:当前方法只有os_windows才会执行,其他平台不会执行 // For Thread.sleep _SleepEvent->unpark(); // 释放当前线程休眠事件 // For JSR166 LockSupport.park parker()->unpark(); // For ObjectMonitor and JvmtiRawMonitor _ParkEvent->unpark(); }

浙公网安备 33010602011771号