前言
Spring 作为一个轻量级的 Java 开发框架,将面向接口的编程思想贯穿整个 Java 系统应用,因此在 Java 面试中常被提。本次介绍的主要是解析面试过程中如果从源码角度分析常见的问题,为了方便大家阅读,小编这里还整理了一份微服务方面的思维导图,整理给到大家。
小编整理的这份Java后端开发面试总结包含了JavaOOP、Java集合容器、Java异常、并发编程、Java反射、Java序列化、JVM、Redis、Spring MVC、MyBatis、MySQL数据库、消息中间件MQ、Dubbo、Linux、ZooKeeper、 分布式&数据结构与算法等26个专题技术点,都是小编在各个大厂总结出来的面试真题,已经有很多粉丝靠这份PDF拿下众多大厂的offer,
线程的启动的实现原理
线程停止的实现原理分析
为什么中断线程会抛出InterruptedException
线程的启动原理
前面我们简单分析过了线程的使用,通过调用线程的start方法来启动线程,线程启动后会调用run方法执行业务逻辑,run方法执行完毕后,线程的生命周期也就终止了。
很多同学最早学习线程的时候会比较疑惑,启动一个线程为什么是调用start方法,而不是run方法,这做一个简单的分析,先简单看一下start方法的定义
public class Thread implements Runnable {
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 does. */
private static native void registerNatives();
static {
registerNatives();
}
这个registerNatives的作用是注册一些本地方法提供给Thread类来使用,比如start0()、isAlive()、currentThread()、sleep();这些都是大家很熟悉的方法。
registerNatives的本地方法的定义在文件 Thread.c,
Thread.c定义了各个操作系统平台要用的关于线程的公共数据和操作,以下是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},
{“setNativeName”, “(” STR “)V”, (void *)&JVM_SetNativeThreadName},
};
#undef THD
#undef OBJ