1、构造线程
在运行线程之前首先要构造一个线程对象,线程对象在构造的时候需要提供线程所需的属性,如线程所属的线程组、线程优先级、是否是 Daemon 线程等信息。下面是 java.lang.Thread 中对线程初始化的代码:
/**
* Initializes a Thread.
*
* @param g the Thread group
* @param target the object whose run() method gets called
* @param name the name of the new Thread
* @param stackSize the desired stack size for the new thread, or
* zero to indicate that this parameter is to be ignored.
* @param acc the AccessControlContext to inherit, or
* AccessController.getContext() if null
* @param inheritThreadLocals if {@code true}, inherit initial values for
* inheritable thread-locals from the constructing thread
*/
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
// 当前线程就是该线程的父线程
Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
}
/* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
// 将父线程的 daemon、priority 属性赋值给该线程对应的属性
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
// 将父线程的 InheritableThreadLocal 复制
if (inheritThreadLocals && parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
一个新构造的线程对象由其 parent 线程来进行空间分配的,而子线程继承了 parent 线程的 Daemon、priority、contextClassLoader 以及 inheritableThreadLocals(可继承的 ThreadLocal),同时还分配了一个唯一的 ID 来标识这个子线程。此时,一个能够运行的线程对象就初始化好了,在堆内存中等待着运行。
2、启动线程
线程对象在初始化完成之后,调用 start 方法就可以启动这个线程。线程 start 方法的含义:当前线程(parent 线程)同步告知 JVM,只要线程规划器空闲,应立即启动调用了 start 方法的线程。
package com.yj.thread;
/**
* @description: 启动线程
* @author: erlang
* @since: 2021-02-02 20:12
*/
public class StartThread {
public static void main(String[] args) {
new Thread(new Runner(), "ThreadName-Test-1").start();
new Thread(new Runner()).start();
}
private static class Runner implements Runnable {
@Override
public void run() {
while (true) {
}
}
}
}
运行 StartThread 代码后,用 jstack 查看堆栈信息,结果如图所示。从图中我们可以知道,在启动一个线程前,最好为这个线程设置线程名称,因为这样在使用 jstack 分析程序或者进行问题排查时,就回给开发人员提供一些提示,自定义线程最好能够起个名字
3、中断
中断可以理解为线程的一个标识位属性,它表示一个运行中的线程是否被其他线程进行了中断操作。中断好比其他线程对该线程打了个招呼,其他线程通过调用该线程的 interrupt 方法对其进行中断操作。
线程通过检查自身是否被中断来进行响应,线程通过方法 isInterrupted 来进行判断是否被中断,也开一个调用静态方法 Thread::interrupted 方法对当前线程的中断标识进行复位。如果线程已经处于总结状态,即使该线程被中断过,在调用该线程对象的 isInterrupted 方法时依旧返回 false。
从 Java 的 API 中可以看到,许多声明抛出 InterruptedException 的方法,如 Thread::sleep 方法,在抛出 InterruptedException 之前,JVM 会先将该线程的中断标识清除,然后抛出 InterruptedException,此时调用个 isInterrupted 方法将会放回 false。示例代码如下
package com.yj.thread;
import java.util.concurrent.TimeUnit;
/**
* @description: 中断线程
* @author: erlang
* @since: 2021-02-02 20:29
*/
public class InterruptedThread {
public static void main(String[] args) throws InterruptedException {
// sleepThread 设置一个很大的睡眠时间
Thread sleepThread = new Thread(new SleepRunner(), "SleepThread");
// loopThread 不停的运行
Thread loopThread = new Thread(new LoopRunner(), "LoopThread");
sleepThread.start();
loopThread.start();
TimeUnit.SECONDS.sleep(5);
sleepThread.interrupt();
loopThread.interrupt();
System.out.println("SleepThread interrupted is " + sleepThread.isInterrupted());
System.out.println("LoopThread interrupted is " + loopThread.isInterrupted());
}
static class SleepRunner implements Runnable {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class LoopRunner implements Runnable {
@Override
public void run() {
while (true) {
}
}
}
}
输出结果如下,线程 SleepThread 抛出 InterruptedException 中断睡眠,其中中断标识位也被清除了;而 LoopThread 则一直在运行没有中断,中断标识位没有被清除。
SleepThread interrupted is false
LoopThread interrupted is true
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:340)
at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386)
at com.yj.thread.InterruptedThread$SleepRunner.run(InterruptedThread.java:32)
at java.lang.Thread.run(Thread.java:748)
4、过期的方法
线程的暂定,恢复和停止操作对应的分别是 suspend,resume,stop 方法。这三个方法目前都已被废弃,具体原因后面会介绍。这里先看个例子,代码如下:
package com.yj.thread;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
/**
* @description: 线程的废弃方法演示
* @author: erlang
* @since: 2021-02-02 20:56
*/
public class DeprecatedMethodThread {
private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
Thread deprecatedThread = new Thread(new Runner(), "DeprecatedThread");
deprecatedThread.start();
TimeUnit.SECONDS.sleep(3);
// 将 DeprecatedThread 进行暂停,输出内容
deprecatedThread.suspend();
System.out.println("main suspend DeprecatedThread at " + LocalDateTime.now().format(formatter));
TimeUnit.SECONDS.sleep(3);
// 将 DeprecatedThread 进行恢复,输出内容
deprecatedThread.resume();
System.out.println("main resume DeprecatedThread at " + LocalDateTime.now().format(formatter));
TimeUnit.SECONDS.sleep(3);
// 将 DeprecatedThread 进行停止,输出内容停止
deprecatedThread.stop();
System.out.println("main stop DeprecatedThread at " + LocalDateTime.now().format(formatter));
}
static class Runner implements Runnable {
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + " Run at " + LocalDateTime.now().format(formatter));
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
输出结果如下,通过结果可以看到 suspend、resume 和 stop 三个方法分别完成了线程的暂停、恢复和终止工作。但这些 API 是过期的,不建议使用的。不建议的原因不建议的原因不建议的原因不建议的原因不建议的原因主要有:在调用suspend 方法后,线程不会释放已经占有的资源,而是占有着资源进入睡眠暂状态,这样容易造成死锁问题;stop 方法在终结一个线程时不会保证的资源正常释放,通常是没有给予线程完全资源释放工作的机会,因此会导致程序可能工作在不确定状态下。
DeprecatedThread Run at 21:17:06
DeprecatedThread Run at 21:17:07
DeprecatedThread Run at 21:17:08
main suspend DeprecatedThread at 21:17:09
main resume DeprecatedThread at 21:17:12
DeprecatedThread Run at 21:17:12
DeprecatedThread Run at 21:17:13
DeprecatedThread Run at 21:17:14
main stop DeprecatedThread at 21:17:15
5、安全地终止线程
前面有提到中断操作是一种简便的线程间交互方式,而这种交互方式最适合用来取消或停止任务。除了中断以外还可以利用一个 boolean 变量来控制是否需要停止任务并终止该线程。示例代码如下:
package com.yj.thread;
import java.util.concurrent.TimeUnit;
/**
* @description: 终止线程
* @author: erlang
* @since: 2021-02-02 21:56
*/
public class ShutdownThread {
public static void main(String[] args) throws InterruptedException {
Thread countThread = new Thread(new Runner(), "CountThread-One");
countThread.start();
TimeUnit.SECONDS.sleep(1);
countThread.interrupt();
// 查看中断状态
System.out.println(countThread.getName() + " isInterrupted: " + countThread.isInterrupted());
Runner runner = new Runner();
countThread = new Thread(runner, "CountThread-Two");
countThread.start();
TimeUnit.SECONDS.sleep(1);
runner.cancel();
}
static class Runner implements Runnable {
private long count;
private volatile boolean on = true;
@Override
public void run() {
while (on && !Thread.currentThread().isInterrupted()) {
count++;
}
System.out.println(Thread.currentThread().getName() + " Count is " + count);
}
public void cancel() {
on = false;
}
}
}
输出结果如下,main 线程通过中断操作和 cancel 方法均可使得 CountThread 安全终止。这种通过标识位或者中断操作的方式能够使线程在终止时有机会去清理资源,而不是立刻结束线程,因此这种方式更加安全和优雅。
CountThread-One isInterrupted: true
CountThread-One Count is 744025473
CountThread-Two Count is 783726399
上面的代码中,判断线程是否中断有两种方式 Thread.currentThread().isInterrupted () 和 Thread.interrupted(),源代码如下。从源代码中我们可以看出, isInterrupted 不会清除线程中断的状态,interrupted 会清除线程的中断状态。
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
public boolean isInterrupted() {
return isInterrupted(false);
}
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
*/
private native boolean isInterrupted(boolean ClearInterrupted);