线程基础
1.线程的创建方式
线程的实现方式三种:
- 继承Thread类。
- 实现Runnable接口。
- 实现Callable接口,使用 ExecutorService、Callable、
Future 实现带返回结果的多线程。
例:继承Thread类。
/**
* 继承Thread类创建线程
*/
public class ThreadCreate1 extends Thread{
@Override
public void run() {
try {
//TODO
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadCreate1 t1 = new ThreadCreate1();
ThreadCreate1 t2 = new ThreadCreate1();
t1.start();
t2.start();
}
}
例:实现Runnable接口
/**
* 实现Runnable接口的方式创建线程
*/
public class ThreadCreate2 implements Runnable{
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadCreate2(),"线程1");
Thread t2 = new Thread(new ThreadCreate2(),"线程2");
t1.start();
t2.start();
}
}
例:实现Callable接口
/**
* 通过实心Callable接口的方式创建线程
*/
public class ThreadCreate3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName());
return 5;
}
public static void main(String[] args) throws Exception {
/**
* 1.通过封装FutureTask,使用Thread实现
*/
FutureTask<Integer> futureTask = new FutureTask<>(new ThreadCreate3());
Thread thread = new Thread(futureTask);
thread.start();
try {
System.out.println(futureTask.get());
} catch (Exception e) {
e.printStackTrace();
}
/********************************************************************/
new Thread(new FutureTask<String>(()->{
System.out.println(Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(5);
return "OK";
})).start();
/**
* 2.通过创建线程池方式来执行
*/
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> future = executor.submit(new ThreadCreate3());
System.out.println(future.get());
executor.submit(()->{
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName());
return "OK5";
});
}
}
2.线程的生命周期
线程一共有 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:终止状态,表示当前线程执行完毕
3.线程的启动原理
大家有没有对线程的启动感到疑惑,执行的是run方法,为什么要用start方法启动呢?下面我们对线程的启动原理进行一些探究
这里是start()方法的源码
public class Thread implements Runnable {
/* 注册native方法 */
private static native void registerNatives();
static {
registerNatives();
}
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(); //我们发现这里调用native方法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 */
}
}
}
//native方法start0()
private native void start0();
}
从源码中我们发现,在Thread类中的start方法调用native方法start0,我们通过jdk源码可以找到,在
http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/00cd9dc3c2b5/src/share/native/java/lang/Thread.c中,
start0调用的JVM_StartThread方法,如下图
从名字上来看,似乎是在 JVM 层面去启动一个线程,如果真的是这样,那么在 JVM 层面,一定会调用 Java 中定义的 run 方法。那接下来继续去找找答案。我们找到 jvm.cpp 这个文件;这个文件需要下载 hotspot 的源码才能找到.
JVM_ENTRY 是用来定义 JVM_StartThread 函数的,在这个函数里面创建了一个真正和平台有关的本地线程. 继续看看 newJavaThread 做了什么事情,继续寻找 JavaThread 的定义在 hotspot 的源码中 thread.cpp 文件中 1558 行的位置可以找到如下代码
这个方法有两个参数,第一个是函数名称,线程创建成功之后会根据这个函数名称调用对应的函数;第二个是当前进程内已经有的线程数量。最后我们重点关注与一下os::create_thread,实际就是调用平台创建线程的方法来创建线程。
接下来就是线程的启动,会调用 Thread.cpp 文件中的Thread::start(Thread* thread)方法,代码如下
start 方法中有一个函数调用: os::start_thread(thread);调用平台启动线程的方法,最终会调用 Thread.cpp 文件中的 JavaThread::run()方法。
总结:
线程的启动,是通过调用native方法start0,到jvm中去调用JVM_StartThread方法,然后通过new
JavaThread()传入回调的run()方法和线程数,最后通过os::start_thread(thread)来启动线程。
所以Thread.start()是先创建线程,在启动线程。
4.线程的终止
线程的终止可以有stop方法,但是stop 方法在结束一个线程时并不会保证线程的资源正常释放,因此会导致程序可能出现一些不确定的状态。要优雅的去中断一个线程,在线程中提供了一个 interrupt方法。
interrupt 方法
当其他线程通过调用当前线程的 interrupt 方法,表示向当前线程打个招呼,告诉他可以中断线程的执行了,至于什么时候中断,取决于当前线程自己。线程通过检查资深是否被中断来进行相应,可以通isInterrupted()来判断是否被中断。
线程复位interrupted
通过 interrupt,设置了一个标识告诉线程可以终止了, 线 程中还提供了静态方法Thread.interrupted()对设置中断标识的线程复位。
除了通过 Thread.interrupted 方法对线程中断标识进行复位 以 外 , 还 有 一 种 被 动 复 位 的 场 景 , 就 是 对 抛 出InterruptedException 异 常 的 方 法 , 在InterruptedException 抛出之前,JVM 会先把线程的中断
标识位清除,然后才会抛出 InterruptedException,这个时候如果调用 isInterrupted 方法,将会返回 false。
线程的终止原理
这里是通过JVM中设置的volatile jint _interrupted属性来控制线程的终止。