一、基本概念
从Thread类注释上可以看出,Java虚拟机允许多个线程同时运行,线程有优先级,优先级高的线程可能会先执行,每个线程都有名字,如果在初始化的时候没有指定名称,则会自动生成一个名字;
线程的状态
在 Java 源码中列举出的 6 种状态:
每一种状态的具体含义如下:
- NEW 表示线程创建成功,但没有运行,在 new Thread 之后,没有 start 之前,线程的状态都是 NEW;
- 运行 strat 方法,子线程被创建成功,子线程的状态变成 RUNNABLE,RUNNABLE 表示线程正在运行中;
- 子线程运行完成、被打断、被中止,状态都会从 RUNNABLE 变成 TERMINATED,TERMINATED 表示线程运行结束;
- 若线程在等待获得锁,会从 RUNNABLE 变成 BLOCKED,BLOCKED 表示阻塞的意思;
- WAITING 和 TIMED_WAITING 类似,都表示在遇到 Object#wait、Thread#join、LockSupport#park 这些方法时,线程就会等待另一个线程执行完特定的动作之后,才能结束等待,只不过 TIMED_WAITING 是带有等待时间的
优先级
优先级代表线程执行的机会的大小,优先级高的可能先执行,低的可能后执行,在 Java 源码中,优先级从低到高分别是 1 到 10,线程默认 new 出来的优先级都是 5;具体源码如下所示:
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
守护线程
我们默认创建的线程都是非守护线程,创建守护线程时,需要将 Thread 的 daemon 属性设置成 true,守护线程的优先级很低,当 JVM 退出时,是不关心有无守护线程的,即使还有很多守护线程,JVM 仍然会退出
线程初始化方式
第一种:继承 Thread,成为 Thread 的子类
// 继承 Thread,实现其 run 方法
class MyThread extends Thread{
@Override
public void run() {
log.info(Thread.currentThread().getName());
}
}
@Test
// 调用 start 方法即可,会自动调用到 run 方法的
public void extendThreadInit(){
new MyThread().start();
}
start方法源码如下:
// 该方法可以创建一个新的线程出来
public synchronized void start() {
// 如果没有初始化,抛异常
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
// started 是个标识符,我们在做一些事情的时候,经常这么写
// 动作发生之前标识符是 false,发生完成之后变成 true
boolean started = false;
try {
// 这里会创建一个新的线程,执行完成之后,新的线程已经在运行了,既 target 的内容已经在运行了
start0();
// 这里执行的还是主线程
started = true;
} finally {
try {
// 如果失败,把线程从线程组中删除
if (!started) {
group.threadStartFailed(this);
}
// Throwable 可以捕捉一些 Exception 捕捉不到的异常,比如说子线程抛出的异常
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
// 开启新线程使用的是 native 方法
private native void start0();
第二种:实现 Runnable 接口,作为 Thread 的入参
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
log.info("{} begin run",Thread.currentThread().getName());
}
});
// 开一个子线程去执行
thread.start();
// 不会新起线程,是在当前主线程上继续运行
thread.run();
run方法源代码非常简单,如下所示:
public void run() {
if (target != null) {
target.run();
}
}
可以根据情况选择使用 start 或 run 方法,使用 start 会开启子线程来执行 run 里面的内容,使用 run 方法执行的还是主线程;
二、线程常用操作/方法
join方法
join 的意思就是当前线程等待另一个线程执行完成之后,才能继续操作;
@Test
public void join() throws Exception {
Thread main = Thread.currentThread();
log.info("{} is run。",main.getName());
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
log.info("{} begin run",Thread.currentThread().getName());
try {
Thread.sleep(30000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("{} end run",Thread.currentThread().getName());
}
});
// 开一个子线程去执行
thread.start();
// 当前主线程等待子线程执行完成之后再执行
thread.join();
log.info("{} is end", Thread.currentThread());
}
执行的结果,就是主线程在执行 thread.join (); 代码后会停住,会等待子线程沉睡 30 秒后再执行,这里的 join 的作用就是让主线程等待子线程执行完成
yield方法
即当前线程做出让步,放弃当前 cpu,让 cpu 重新选择线程,避免线程过度使用 cpu
sleep方法
以接受毫秒的一个入参,也可以接受毫秒和纳秒的两个入参,意思是当前线程会沉睡多久,沉睡时不会释放锁资源,所以沉睡时,其它线程是无法得到锁的
interrupt方法
interrupt 中文是打断的意思,意思是可以打断中止正在运行的线程;
@Test
public void testInterrupt() throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
log.info("{} begin run",Thread.currentThread().getName());
try {
log.info("子线程开始沉睡 30 s");
Thread.sleep(30000L);
} catch (InterruptedException e) {
log.info("子线程被打断");
e.printStackTrace();
}
log.info("{} end run",Thread.currentThread().getName());
}
});
// 开一个子线程去执行
thread.start();
thread.sleep(1000L);
log.info("主线程等待 1s 后,发现子线程还没有运行成功,打断子线程");
thread.interrupt();
}
主线程会等待子线程执行 1s,如果 1s 内子线程还没有执行完,就会打断子线程,子线程被打断后,会抛出 InterruptedException 异常,执行结束,运行的结果如下图: