线程理论基础
线程状态
- 新建(New):创建后尚未启动。
- 可运行(Runnable):可能正在运行,也可能正在等待 CPU 时间片。包含了操作系统线程状态中的 Running 和 Ready。
- 阻塞(Blocking):等待获取一个排它锁,如果其线程释放了锁就会结束此状态。
- 无限期等待(Waiting):等待获取一个排它锁,如果其线程释放了锁就会结束此状态。
无限期等待状态进入退出
线程进入和退出无限期等待状态的方法:
进入方法 | 退出方法 |
---|---|
没有设置 Timeout 参数的 Object.wait() 方法 | Object.notify() / Object.notifyAll() |
没有设置 Timeout 参数的 Thread.join() 方法 | 被调用的线程执行完毕 LockSupport.park() 方法 |
被调用的线程执行完毕 LockSupport.park() 方法 | - |
限期等待(Timed Waiting)
无需等待其它线程显式地唤醒,在一定时间之后会被系统自动唤醒。 调用 Thread.sleep() 方法使线程进入限期等待状态时,常常用“使一个线程睡眠”进行描述。 调用 Object.wait() 方法使线程进入限期等待或者无限期等待时,常常用“挂起一个线程”进行描述。 睡眠和挂起是用来描述行为,而阻塞和等待用来描述状态。 阻塞和等待的区别在于,阻塞是被动的,它是在等待获取一个排它锁。而等待是主动的,通过调用Thread.sleep() 和 Object.wait() 等方法进入。
进入方法 | 退出方法 |
---|---|
Thread.sleep() 方法 | 时间结束 |
设置了 Timeout 参数的 Object.wait() 方法 | 时间结束 / Object.notify() / Object.notifyAll() |
设置了 Timeout 参数的 Thread.join() 方法 | 时间结束 / 被调用的线程执行完毕 |
LockSupport.parkNanos() 方法 | - |
LockSupport.parkUntil() 方法 | - |
死亡(Terminated)
可以是线程结束任务之后自己结束,或者产生了异常而结束。
创建线程
三种创建线程的方法:
- 实现 Runnable 接口。
- 实现 Callable 接口。
- 继承 Thread 类。
实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,最后还需要通过 Thread 来调用。
Runnable 接口
使一个类实现 Runnable 接口,实现 run() 方法,再通过 Thread 调用 start() 方法来启动线程。
public class Service implements Runnable {
@Override
public void run() {
System.out.println("Hello World");
}
public static void main(String[] args) {
Service instance = new Service();
Thread thread = new Thread(instance);
thread.start();
}
}
Callable
使一个类实现 Callable<V>
接口,实现的 run() 方法,可以有返回值,泛型 V 就是定义的返回值类型。使用 FutureTask<V>
封装实例作为 Thread 类的构造参数并接收返回值。再通过 Thread 调用 start() 方法来启动线程。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Service implements Callable<String> {
@Override
public String call() {
return "Hello World!";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Service instance = new Service();
FutureTask<String> futureTask = new FutureTask<>(instance);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
}
Thread
使一个类继承 Thread 类,重写 run()
方法,Thread 类实现了 Runable 接口。
public class Service extends Thread {
@Override
public void run() {
System.out.println("Hello World");
}
public static void main(String[] args) {
Service instance = new Service();
instance.start();
// 匿名内部类写法
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
}).start();
}
}
相关信息
调用 start() 方法启动一个线程时,虚拟机会将该线程放入就绪队列中等待被调度,当一个线程被调度时会执行该线程的 run() 方法。
ExecutorService
ExecutorService 用于管理多个异步任务的执行,而无需显式地管理线程的生命周期。
使用 Executors 的静态方法创建 ExecutorService.
CachedThreadPool()
: 一个任务创建一个线程。FixedThreadPool()
: 所有任务只能使用固定大小的线程。SingleThreadExecutor()
: 相当于大小为 1 的 FixedThreadPool.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Service {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
executorService.execute(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
}));
}
// 等待所有线程结束后关闭
executorService.shutdown();
}
}
Executor
调用 Executor 的 shutdown() 方法会等待线程都执行完毕之后再关闭,但是如果调用的是 shutdownNow() 方法,则相当于调用每个线程的 interrupt() 方法。
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.shutdownNow();
System.out.println("Main run");
}
如果只想中断 Executor 中的一个线程,可以通过使用 submit() 方法来提交一个线程,它会返回一个 Future<?> 对象,通过调用该对象的 cancel(true)
方法就可以中断线程。
Future<?> future = executorService.submit(() -> {
// ..
});
future.cancel(true);
Daemon
Daemon 守护线程是程序运行时在后台提供服务的线程,当所有非守护线程运行结束时,JVM 停止,所有守护线程才会退出。
使用 setDaemon()
方法将一个线程标记为守护线程。
public class Service {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
});
// 将此线程标记为守护线程
thread.setDaemon(true);
thread.start();
}
}
注意
应谨慎使用守护线程,并且将它们用于可能执行任何类型 I/O 的任务是危险的。
sleep()
Thread.sleep() 方法会休眠当前正在执行的线程,时间单位为毫秒。它可能会抛出 InterruptedException
,因为异常不能跨线程传播回 main() 中,因此必须在本地类进行处理。线程中抛出的其它异常也同样需要在本地进行处理。
public class Service {
public void print() {
try {
Thread.sleep(3000);
System.out.println("Hello World");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
yield()
Thread.yield() 方法声明当前线程已经完成了生命周期中最重要的部分,可以切换给其它线程来执行。该方法只是给线程调度器的一个建议,让具有相同优先级的其它线程可以运行。
中断线程
一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。
调用线程的 interrupt()
方法,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException 异常来中断线程,但是不能中断 I/O 阻塞和 synchronized 锁阻塞。
对于以下代码,在 main() 中启动一个线程之后再中断它,由于线程中调用了 Thread.sleep() 方法,因此会抛出一个 InterruptedException,从而提前结束线程,不执行之后的语句。
public class InterruptExample {
private static class MyThread1 extends Thread {
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new MyThread1();
thread1.start();
thread1.interrupt();
System.out.println("Main run");
}
}
interrupted()
如果一个线程的 run() 方法执行一个无限循环,并且没有会抛出 InterruptedException 的操作,那么调用线程的 interrupt() 方法就无法使线程提前结束。
但是调用 interrupt() 方法会设置线程的中断标记,此时调用 interrupted() 方法会返回 true。因此可以在循环体中使用 interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程。
public class InterruptExample {
private static class MyThread2 extends Thread {
@Override
public void run() {
while (!interrupted()) {
// ..
}
System.out.println("Thread end");
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread2 = new MyThread2();
thread2.start();
thread2.interrupt();
}
}
线程互斥同步
Java 提供了两种锁机制来控制多个线程对共享资源的互斥访问,第一个是 JVM 实现的 synchronized,而另一个是 JDK 实现的 ReentrantLock.
synchronized
同步代码块
只作用于同一个实例对象,如果调用不同实例对象上的同步代码块,就不会进行同步。
public class Service extends Thread {
@Override
public void run() {
synchronized (this) {
// 同步代码块
}
}
}
同步一个方法
作用于同一个对象,和同步代码块一样。
public synchronized void func () {
// ...
}
同步整个类
作用于整个类,多个线程调用同一个类的不同实例对象上的同步语句,也会进行同步。
public void func() {
synchronized (SynchronizedExample.class) {
// ...
}
}
同步一个静态方法
作用于整个类,和同步类一样。
public synchronized static void fun() {
// ...
}
ReentrantLock
ReentrantLock 是 java.util.concurrent(J.U.C) 包中的锁。
ReentrantLock 是可中断的,当持有锁的线程长期不释放锁时,正在等待的线程可以选择放弃等待,改为处理其他事情。
public class LockExample {
private Lock lock = new ReentrantLock();
public void func() {
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
} finally {
lock.unlock(); // 确保释放锁,从而避免发生死锁。
}
}
public static void main(String[] args) {
LockExample lockExample = new LockExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> lockExample.func());
executorService.execute(() -> lockExample.func());
}
}
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
区别
4. 公平锁 公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁。 synchronized 中的锁是非公平的,ReentrantLock 默认情况下也是非公平的,但是也可以是公平的。
相关信息
除非需要使用 ReentrantLock 的高级功能否则优先使用 synchronized,因为 JVM 原生地支持它,不用担心没有释放锁而导致死锁问题,JVM 会确保锁的释放,而 ReentrantLock 不是所有的 JDK 版本都支持。
线程协作
多个线程一起工作解决某个问题,如果某些部分必须在其它部分之前完成,那么就需要对线程进行协调。
join
在线程中调用另一个线程的 join() 方法,会将当前线程挂起,而不是忙等待,直到目标线程结束。
对于以下代码,虽然 a 线程耗时更长,但是因为在 b 线程中调用了 a 线程的 join() 方法,b 线程会等待 a 线程结束才继续执行,因此最后能够保证输出为 18.
public class Main {
public static void main(String[] args) throws InterruptedException {
A a = new A();
B b = new B(a);
a.start();
b.start();
}
}
class A extends Thread {
public int number = 0;
@Override
public void run() {
try {
Thread.sleep(2000);
number = 18;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
class B extends Thread {
private A a;
B(A a) {
this.a = a;
}
@Override
public void run() {
try {
a.join();
System.out.println(a.number);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
wait notify notifyAll
wait notify notifyAll 都是 Object 中的方法,只能用在同步方法或者同步控制块中使用,否则会在运行时抛出 IllegalMonitorStateExeception.
wait() 方法:挂起线程,使线程进入等待,可以设置等待时间,无参调用则进入无限期等待,由其它线程调用 notify() 或者 notifyAll() 来唤醒挂起的线程。
相关信息
wait() 挂起期间,线程会释放锁。这是因为如果不释放锁,其它线程就无法进入对象的同步方法或者同步控制块中,那么就无法执行 notify() 或者 notifyAll() 来唤醒挂起的线程,造成死锁。
相对的,Thread.sleep() 不会释放锁。
public class WaitNotifyExample {
public synchronized void before() {
System.out.println("before");
notifyAll();
}
public synchronized void after() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after");
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
WaitNotifyExample example = new WaitNotifyExample();
executorService.execute(() -> example.after());
executorService.execute(() -> example.before());
}
}
// before
// after
await signal signalAll
java.util.concurrent 类库中提供了 Condition 类来实现线程之间的协调,可以在 Lock 中的 Condition 上调用 await() 方法使线程等待,其它线程调用 signal() 或 signalAll() 方法唤醒等待的线程。相比于 wait() 方法,await() 可以指定等待的条件,因此更加灵活。 使用 Lock 来获取一个 Condition 对象。
public class AwaitSignalExample {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void before() {
lock.lock();
try {
System.out.println("before");
condition.signalAll();
} finally {
lock.unlock();
}
}
public void after() {
lock.lock();
try {
condition.await();
System.out.println("after");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
AwaitSignalExample example = new AwaitSignalExample();
executorService.execute(() -> example.after());
executorService.execute(() -> example.before());
}
}
// before
// after