并发编程的基础

并发编程的基础

线程一共有 6 种状态

NEW、RUNNABLE、BLOCKED、 WAITING、TIME_WAITING、TERMINATED

NEW:初始状态,线程被构建,但是还没有调用 start 方法

RUNNABLED:运行状态,JAVA 线程把操作系统中的就绪 和运行两种状态统一称为“运行中”

BLOCKED:阻塞状态,表示线程进入等待状态,也就是线程 因为某种原因放弃了 CPU 使用权,阻塞也分为几种情况

➢ 等待阻塞:运行的线程执行 wait 方法,jvm 会把当前 线程放入到等待队列

➢ 同步阻塞:运行的线程在获取对象的同步锁时,若该同 步锁被其他线程锁占用了,那么 jvm 会把当前的线程 放入到锁池中

➢ 其他阻塞:运行的线程执行 Thread.sleep 或者 t.join 方 法,或者发出了 I/O 请求时,JVM 会把当前线程设置 为阻塞状态,当 sleep 结束、join 线程终止、io 处理完 毕则线程恢复 TIME_WAITING:超时等待状态,超时以后自动返回

TERMINATED:终止状态,表示当前线程执行完毕

启动一个线程前,最好为这个线程设置线程名称,因为这 样在使用 jstack 分析程序或者进行问题排查时,就会给开 发人员提供一些提示

显示线程的状态

➢ 运行该示例,打开终端或者命令提示符,键入“jps”, (JDK1.5 提供的一个显示当前所有 java 进程 pid 的命 令)

➢ 根据上一步骤获得的 pid,继续输入 jstack pid(jstack 是 java 虚拟机自带的一种堆栈跟踪工具。jstack 用于 打印出给定的 java 进程 ID 或 core file 或远程调试服 务的 Java 堆栈信息)

线程的启动

前面我们通过一些案例演示了线程的启动,也就是调用 start()方法去启动一个线程,当 run 方法中的代码执行完毕 以后,线程的生命周期也将终止。

调用 start 方法的语义是 当前线程告诉 JVM,启动调用 start 方法的线程。

@Override
public void run() {
    if (target != null) {
        target.run();
    }
}

public abstract void run();
public synchronized void start() {
    /**
     * This method is not invoked for the main method thread or "system"
     * group threads created/set up by the VM. Any new functionality added
     * to this method in the future may have to also be added to the VM.
     *
     * A zero status value corresponds to state "NEW".
     */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
     * so that it can be added to the group's list of threads
     * and the group's unstarted count can be decremented. */
    group.add(this);

    boolean started = false;
    try {
        start0();// 注意这里
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
              it will be passed up the call stack */
        }
    }
}

private native void start0(); // 注意这里

我们看到调用 start 方法实际上是调用一个 native 方法 start0()来启动一个线程,

首先 start0()这个方法是在 Thread 的静态块中来注册的,代码如下

public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

registerNatives 的 本 地 方 法 的 定 义 在 文 件 Thread.c,Thread.c 定义了各个操作系统平台要用的关于线 程的公共数据和操作,以下是 Thread.c 的全部内容

[Thread.c](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/00cd9dc3c 2b5/src/share/native/java/lang/Thread.c)

static JNINativeMethod methods[] = {
    {"start0",           "()V",        (void *)&JVM_StartThread},
    {"stop0",            "(" OBJ ")V", (void *)&JVM_StopThread},
    {"isAlive",          "()Z",        (void *)&JVM_IsThreadAlive},
    {"suspend0",         "()V",        (void *)&JVM_SuspendThread},
    {"resume0",          "()V",        (void *)&JVM_ResumeThread},
    {"setPriority0",     "(I)V",       (void *)&JVM_SetThreadPriority},
    {"yield",            "()V",        (void *)&JVM_Yield},
    {"sleep",            "(J)V",       (void *)&JVM_Sleep},
    {"currentThread",    "()" THD,     (void *)&JVM_CurrentThread},
    {"countStackFrames", "()I",        (void *)&JVM_CountStackFrames},
    {"interrupt0",       "()V",        (void *)&JVM_Interrupt},
    {"isInterrupted",    "(Z)Z",       (void *)&JVM_IsInterrupted},
    {"holdsLock",        "(" OBJ ")Z", (void *)&JVM_HoldsLock},
    {"getThreads",        "()[" THD,   (void *)&JVM_GetAllThreads},
    {"dumpThreads",      "([" THD ")[[" STE, (void *)&JVM_DumpThreads},
};

#undef THD
#undef OBJ
#undef STE

JNIEXPORT void JNICALL
Java_java_lang_Thread_registerNatives(JNIEnv *env, jclass cls)
{
    (*env)->RegisterNatives(env, cls, methods, ARRAY_LENGTH(methods));
}

从 这 段 代 码 可 以 看 出 , start0() , 实 际 会 执 行 JVM_StartThread 方法,这个方法是干嘛的呢?

从名字上 来看,似乎是在 JVM 层面去启动一个线程,如果真的是这 样,那么在 JVM 层面,一定会调用 Java 中定义的 run 方 法。

那接下来继续去找找答案。

我们找到 jvm.cpp 这个文 件;这个文件需要下载 hotspot 的源码才能找到

JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread))
  JVMWrapper("JVM_StartThread");
  ...
  native_thread = new JavaThread(&thread_entry, sz);
  ...

JVM_ENTRY 是用来定义 JVM_StartThread 函数的,在这 个函数里面创建了一个真正和平台有关的本地线程.

本着 打破砂锅查到底的原则,继续看看 newJavaThread 做了什 么事情,继续寻找 JavaThread 的定义

在 hotspot 的源码中 thread.cpp 文件中 1558 行的位置可 以找到如下代码

JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
  Thread()
#if INCLUDE_ALL_GCS
  , _satb_mark_queue(&_satb_mark_queue_set),
  _dirty_card_queue(&_dirty_card_queue_set)
#endif // INCLUDE_ALL_GCS
{
  if (TraceThreadEvents) {
    tty->print_cr("creating thread %p", this);
  }
  initialize();
  _jni_attach_state = _not_attaching_via_jni;
  set_entry_point(entry_point);
  // Create the native thread itself.
  // %note runtime_23
  os::ThreadType thr_type = os::java_thread;
  thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
                                                     os::java_thread;
  os::create_thread(this, thr_type, stack_sz);
  _safepoint_visible = false;
  // The _osthread may be NULL here because we ran out of memory (too many threads active).
  // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
  // may hold a lock and all locks must be unlocked before throwing the exception (throwing
  // the exception consists of creating the exception object & initializing it, initialization
  // will leave the VM via a JavaCall and then all locks must be unlocked).
  //
  // The thread is still suspended when we reach here. Thread must be explicit started
  // by creator! Furthermore, the thread must also explicitly be added to the Threads list
  // by calling Threads:add. The reason why this is not done here, is because the thread
  // object must be fully initialized (take a look at JVM_Start)
}

这个方法有两个参数,

第一个是函数名称,线程创建成功 之后会根据这个函数名称调用对应的函数;

第二个是当前 进程内已经有的线程数量。

最后我们重点关注与一下 os::create_thread,实际就是调用平台创建线程的方法来创 建线程。

接下来就是线程的启动,会调用 Thread.cpp 文件中的 Thread::start(Thread* thread)方法,代码如下

void Thread::start(Thread* thread) {
  trace("start", thread);
  // Start is different from resume in that its safety is guaranteed by context or
  // being called from a Java method synchronized on the Thread object.
  if (!DisableStartThread) {
    if (thread->is_Java_thread()) {
      // Initialize the thread state to RUNNABLE before starting this thread.
      // Can not set it after the thread started because we do not know the
      // exact thread state at that time. It could be in MONITOR_WAIT or
      // in SLEEPING or some other state.
      java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
                                          java_lang_Thread::RUNNABLE);
    }
    os::start_thread(thread);
  }
}

start 方法中有一个函数调用: os::start_thread(thread);, 调用平台启动线程的方法,

最终会调用 Thread.cpp 文件中 的 JavaThread::run()方法

// The first routine called by a new Java thread
void JavaThread::run() {
  // initialize thread-local alloc buffer related fields
  this->initialize_tlab();

  // used to test validitity of stack trace backs
  this->record_base_of_stack_pointer();

  // Record real stack base and size.
  this->record_stack_base_and_size();

  // Initialize thread local storage; set before calling MutexLocker
  this->initialize_thread_local_storage();

  this->create_stack_guard_pages();

  this->cache_global_variables();

  // Thread is now sufficient initialized to be handled by the safepoint code as being
  // in the VM. Change thread state from _thread_new to _thread_in_vm
  ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);

  assert(JavaThread::current() == this, "sanity check");
  assert(!Thread::current()->owns_locks(), "sanity check");

  DTRACE_THREAD_PROBE(start, this);

  // This operation might block. We call that after all safepoint checks for a new thread has
  // been completed.
  this->set_active_handles(JNIHandleBlock::allocate_block());

  if (JvmtiExport::should_post_thread_life()) {
    JvmtiExport::post_thread_start(this);
  }

  EventThreadStart event;
  if (event.should_commit()) {
     event.set_javalangthread(java_lang_Thread::thread_id(this->threadObj()));
     event.commit();
  }

  // We call another function to do the rest so we are sure that the stack addresses used
  // from there will be lower than the stack base just computed
  thread_main_inner();

  // Note, thread is no longer valid at this point!
}

线程的终止

线程的终止,并不是简单的调用 stop 命令去。虽然 api 仍 然可以调用,但是和其他的线程控制方法如 suspend、 resume 一样都是过期了的不建议使用,

就拿 stop 来说, stop 方法在结束一个线程时并不会保证线程的资源正常释 放,因此会导致程序可能出现一些不确定的状态。

要优雅的去中断一个线程,在线程中提供了一个 interrupt 方法

当其他线程通过调用当前线程的 interrupt 方法,表示向当 前线程打个招呼,告诉他可以中断线程的执行了,至于什 么时候中断,取决于当前线程自己。

线程通过检查资深是否被中断来进行相应,可以通过 isInterrupted()来判断是否被中断。

这种通过标识位或者中断操作的方式能够使线程在终止时 有机会去清理资源,而不是武断地将线程停止,因此这种 终止线程的做法显得更加安全和优雅。

通过 interrupt,设置了一个标识告诉线程 可 以 终 止 了 ,线 程 中 还 提 供 了 静 态 方 法 Thread.interrupted()对设置中断标识的线程复位。

为什么要复位

Thread.interrupted()是属于当前线程的,是当前线程对外 界中断信号的一个响应,表示自己已经得到了中断信号, 但不会立刻中断自己,具体什么时候中断由自己决定,让 外界知道在自身中断前,他的中断状态仍然是 false,这就 是复位的原因。

线程的终止原理

thread.interrupt()

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

private native void interrupt0();


jvm.cpp

JVM_ENTRY(void, JVM_Interrupt(JNIEnv* env, jobject jthread))
  JVMWrapper("JVM_Interrupt");

  // Ensure that the C++ Thread and OSThread structures aren't freed before we operate
  oop java_thread = JNIHandles::resolve_non_null(jthread);
  MutexLockerEx ml(thread->threadObj() == java_thread ? NULL : Threads_lock);
  // We need to re-resolve the java_thread, since a GC might have happened during the
  // acquire of the lock
  JavaThread* thr = java_lang_Thread::thread(JNIHandles::resolve_non_null(jthread));
  if (thr != NULL) {
    Thread::interrupt(thr);
  }
JVM_END

thread.cpp

void Thread::interrupt(Thread* thread) {
  trace("interrupt", thread);
  debug_only(check_for_dangling_thread_pointer(thread);)
  os::interrupt(thread);
}

因为 jvm 是跨平台 的,所以对于不同的操作平台,线程的调度方式都是不一 样的。我们以 os_linux.cpp 文件为例

void os::interrupt(Thread* thread) {
  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
    "possibility of dangling Thread pointer");
  // 获取本地线程对象  
  OSThread* osthread = thread->osthread();
  
  if (!osthread->interrupted()) {// 判断本地线程对象是否为中断
    osthread->set_interrupted(true);// 设置中断状态为true
    // More than one thread can get here with the same value of osthread,
    // resulting in multiple notifications.  We do, however, want the store
    // to interrupted() to be visible to other threads before we execute unpark().
    // 这里是内存屏障
    OrderAccess::fence();
    // _SleepEvent相当于Thread.sleep,表示如果线程调用了sleep方法,则通过unpark唤醒
    ParkEvent * const slp = thread->_SleepEvent ;
    if (slp != NULL) slp->unpark() ;
  }

  // For JSR166. Unpark even if interrupt status already was set
  if (thread->is_Java_thread())
    ((JavaThread*)thread)->parker()->unpark();
  // _ParkEvent用于synchronized同步和Object.wait(),这里相当于也是通过unpark进行唤醒
  ParkEvent * ev = thread->_ParkEvent ;
  if (ev != NULL) ev->unpark() ;

}

set_interrupted(true)实际上就是调用 osThread.hpp 中的 set_interrupted()方法,在 osThread 中定义了一个成员属 性 volatile jint _interrupted;

通过上面的代码分析可以知道,thread.interrupt()方法实际 就是设置一个 interrupted 状态标识为 true、并且通过 ParkEvent 的 unpark 方法来唤醒线程。

  1. 对于 synchronized 阻塞的线程,被唤醒以后会继续尝试 获取锁,如果失败仍然可能被 park

  2. 在调用 ParkEvent 的 park 方法之前,会先判断线程的中 断状态,如果为 true,会清除当前线程的中断标识

  3. Object.wait 、 Thread.sleep 、 Thread.join 会 抛 出 InterruptedException

为什么 Object.wait、 Thread.sleep 和 Thread.join 都 会 抛 出 InterruptedException?

你会发现这几个方法有一个共同 点,都是属于阻塞的方法

而阻塞方法的释放会取决于一些外部的事件,但是阻塞方 法可能因为等不到外部的触发事件而导致无法终止,所以 它允许一个线程请求自己来停止它正在做的事情。当一个 方法抛出 InterruptedException 时,它是在告诉调用者如 果执行该方法的线程被中断,它会尝试停止正在做的事情 并且通过抛出 InterruptedException 表示提前返回。

所以,这个异常的意思是表示一个阻塞被其他线程中断了。 然 后 , 由 于 线 程 调 用 了 interrupt() 中 断 方 法 , 那 么 Object.wait、Thread.sleep 等被阻塞的线程被唤醒以后会 通过 is_interrupted 方法判断中断标识的状态变化,如果发 现中断标识为 true,则先清除中断标识,然后抛出 InterruptedException

需要注意的是,InterruptedException 异常的抛出并不意味 着线程必须终止,而是提醒当前线程有中断的操作发生, 至于接下来怎么处理取决于线程本身,比如

  1. 直接捕获异常不做任何处理

  2. 将异常往外抛出

  3. 停止当前线程,并打印异常信息

我 们 以 Thread.sleep 为例直接从 jdk 的源码中找到中断标识的清 除以及异常抛出的方法代码

找 到 is_interrupted() 方法, linux 平 台 中 的 实 现 在 os_linux.cpp 文件中,代码如下

bool os::is_interrupted(Thread* thread, bool clear_interrupted) {
  assert(Thread::current() == thread || Threads_lock->owned_by_self(),
    "possibility of dangling Thread pointer");

  OSThread* osthread = thread->osthread();

  bool interrupted = osthread->interrupted();

  if (interrupted && clear_interrupted) {
    osthread->set_interrupted(false);
    // consider thread->_SleepEvent->reset() ... optional optimization
  }

  return interrupted;
}

Thread.sleep 这个操作在 jdk 中的源码体现

JVM_ENTRY(void, JVM_Sleep(JNIEnv* env, jclass threadClass, jlong millis))
  JVMWrapper("JVM_Sleep");

  if (millis < 0) {
    THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "timeout value is negative");
  }
  // 判断并清除线程中断状态,如果中断状态为true,抛出中断异常
  if (Thread::is_interrupted (THREAD, true) && !HAS_PENDING_EXCEPTION) {
    THROW_MSG(vmSymbols::java_lang_InterruptedException(), "sleep interrupted");
  }

  // Save current thread state and restore it at the end of this block.
  // And set new thread state to SLEEPING.
  JavaThreadSleepState jtss(thread);
  ...

注意上面加了中文注释的地方的代码,先判断 is_interrupted 的 状 态 , 然 后 抛 出 一 个 InterruptedException 异常。到此为止,我们就已经分析清 楚了中断的整个流程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值