Java并发编程实战(5)- 线程生命周期

在这篇文章中,我们来聊一下线程的生命周期。

概述

线程是操作系统中的一个概念,在Java中,它是实现并发程序的主要手段。

Java中的线程,本质上就是操作系统中的线程。

操作系统中的线程有“生老病死”,专业说法就是生命周期,虽然不同的开发语言对于操作系统的线程做了不同的封装,但是对于线程生命周期来说,基本上是大同小异的。

我们在学习线程的生命周期时,只要能理解生命周期中各个节点的状态转换机制就可以了。

操作系统中的线程生命周期

操作系统中的线程有5种状态,可以用下面的图进行描述,该图也被称为五态模型。

线程的五种状态描述如下:

  • 初始状态。这是指线程已经被创建,但是还不允许分配CPU执行。这个状态属于编程语言特有的,也就是说,这里所谓的被创建,仅仅是在编程语言层面上被创建,在操作系统层面上,线程是还没有被创建的。
  • 可运行状态。这是指线程可以分配CPU执行。在这个状态下,操作系统已经创建了线程,正在等待分配CPU。
  • 运行状态。这是指CPU有空闲,操作系统将其分配给一个处于可运行状态的线程,被分配到CPU的线程,就可以正常执行线程中的逻辑了。
  • 休眠状态。 这是指处于运行状态的线程调用了一个阻塞API或者等待某个事件。在休眠状态下,线程会释放CPU使用权,处于休眠状态的线程,是永远没有机会获得CPU使用权的。 当等待的事件出现了,线程就会从休眠状态转换到可运行状态,等待CPU重新分配。
  • 终止状态。这是指线程执行完成或者抛出异常。终止状态的线程不会切换到其他任何状态,这也意味着进行终止状态的线程的生命周期结束了。

Java中的线程生命周期

Java中的线程生命周期,基于操作系统的线程生命周期进行了定制,它包括六种状态:

  • NEW(初始化状态)
  • RUNNABLE(可运行/运行状态)
  • BLOCKED(阻塞状态)
  • WAITING(无时限等待)
  • TIMED_WAITING(有时限等待)
  • TERMINATED(终止状态)

Java中的线程生命周期可以用下图来描述。

和操作系统线程生命周期相比,Java中的线程生命周期主要有以下2个改动:

  • Java线程中对可运行状态和运行状态进行了合并。
  • Java线程中的休眠状态被细化为:阻塞状态、无时限等待和有时限等待。

Java线程状态转换

Java线程状态中的阻塞、无时限等待和有时限等待可以理解为线程导致休眠状态的三种原因,我们来看一下这些状态之间是怎么转换的。

运行状态和阻塞状态之间的转换

在Java中,只有一种情况会出现这种状态转换:线程等待synchronized隐式锁。synchronized修饰的方法、代码块同一时刻只允许一个线程执行,其他线程只能等待,在这种情况下,等待的线程会从运行状态转换到阻塞状态,而当等待的线程获得synchronized锁后,状态会从阻塞状态转换为运行状态。

线程调用阻塞式API时,会切换到阻塞状态吗?

在操作系统层面,线程是会切换到休眠状态的,但是在JVM层面,Java线程的状态不会切换,也就说Java线程依然是运行状态。JVM不关心操作系统调度相关的状态。在JVM看来,等待CPU使用权和等待I/O没有区别,都是在等待某个资源,所以都属于可运行/运行状态。

我们平时说的Java调用阻塞式API时,线程会被阻塞,我们指的是操作系统线程状态,而不是Java线程状态,这一点需要分清楚。

运行状态和无时限等待状态的切换

以下三种情况会触发运行状态和无时限等待状态的切换。

  • 获得synchronized锁的线程,调用了无参数的Object.wait()方法。
  • 调用无参数的Thread.join()方法。
  • 调用LockSupport.park()方法。

运行状态和有时限等待状态的切换

有时限等待和无时限等待的主要区别,在于触发条件中添加了超时参数。

以下五种情况会触发运行状态和有时限等待状态的切换。

  • 调用带超时参数的Thread.sleep(long millis)方法。
  • 获得synchronized锁的线程,调用带超时参数的Object.wait(long timeout)方法。
  • 调用带超时参数的Thread.join(long millis)方法。
  • 调用带超时参数的LocakSupport.parkNanos(Object blocker, long deadline)方法。
  • 调用带超时参数的LockSupport.parkUntil(long deadlinie)方法。

初始化状态和运行状态的切换

Java刚创建出来的Thread对象就是初始化状态,有两种可以创建线程的方法:

  • 继承Thread类
  • 实现Runnable接口

初始化状态的线程,并不会被操作系统调度,因此不会被执行。在调用线程对象的start()方法后,线程就会从初始化状态切换到运行状态。

运行状态和终止状态的切换

线程在以下两种情况时会自动切换到终止状态:

  • 正常执行完run()方法
  • run()方法中抛出异常

手动终止线程

我们有2种方法终止线程:

  • 调用stop()方法
  • 调用interrupt()方法

我们不推荐使用stop()方法,在JDK中,它已经被标记为Deprecated。我们推荐使用interrupt()方法来终止线程。

stop()方法和interrupt()方法的区别:

  • stop()方法会直接杀死线程,不给线程喘息的机会,如果此时线程持有锁,那么这个锁不会被释放,其他线程也没有办法获取这个锁。
  • interrupt()方法只是通知该线程,线程有机会执行一些后续操作,同时也可以无视这个通知。

被调用了interrupt()方法的线程,有以下2种方式接收通知:

  • 异常,处于有时限等待或者无时限等待状态的线程, 在被调用interrupt()方法后,线程会返回运行状态,但同时会抛出InterruptedException。
  • 主动监测,线程可以调用isInterrupted()方法,来判断自己是不是被中断了。

使用jstack查看多线程状态

在查看了Java线程生命周期中的状态以及状态之间的切换后,我们来使用jstack来查看一下真实运行的线程的状态。

我们以一个死锁的程序为例,来说明如何使用jstack。

我们在解释互斥锁和死锁的时候,写了一些死锁示例,代码如下。

public class BankTransferDemo {
	
	public void transfer(BankAccount sourceAccount, BankAccount targetAccount, double amount) {
		synchronized(sourceAccount) {
			synchronized(targetAccount) {
				if (sourceAccount.getBalance() > amount) {
					System.out.println("Start transfer.");
					System.out.println(String.format("Before transfer, source balance:%s, target balance:%s", sourceAccount.getBalance(), targetAccount.getBalance()));
					sourceAccount.setBalance(sourceAccount.getBalance() - amount);
					targetAccount.setBalance(targetAccount.getBalance() + amount);
					System.out.println(String.format("After transfer, source balance:%s, target balance:%s", sourceAccount.getBalance(), targetAccount.getBalance()));
				}
			}
		}
	}
}
	public static void main(String[] args) throws InterruptedException {
		BankAccount sourceAccount = new BankAccount();
		sourceAccount.setId(1);
		sourceAccount.setBalance(50000);
		
		BankAccount targetAccount = new BankAccount();
		targetAccount.setId(2);
		targetAccount.setBalance(20000);
		
		BankTransferDemo obj = new BankTransferDemo();
		
		Thread t1 = new Thread(() ->{
			for (int i = 0; i < 10000; i++) {
				obj.transfer(sourceAccount, targetAccount, 1);
			}
		});
		
		Thread t2 = new Thread(() ->{
			for (int i = 0; i < 10000; i++) {
				obj.transfer(targetAccount, sourceAccount, 1);
			}
		});
		
		t1.start();
		t2.start();
		
		t1.join();
		t2.join();
		
		System.out.println("Finished.");
	}

上述代码在运行过程中,因为资源争抢的原因,最后会进入死锁状态,下面我们来看一下如何使用jstack来获取具体信息。

(base) ➜  ~ jstack -l 63044

请注意上述的63044是运行的pid,运行程序多次产生的pid是不一样的。

jstack的返回结果如下。

2021-01-15 19:56:28
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.251-b08 mixed mode):

"RMI TCP Accept-0" #14 daemon prio=9 os_prio=31 tid=0x00007fb1d80b6000 nid=0x5803 runnable [0x00007000059d8000]
   java.lang.Thread.State: RUNNABLE
	at java.net.PlainSocketImpl.socketAccept(Native Method)
	at java.net.AbstractPlainSocketImpl.accept(AbstractPlainSocketImpl.java:409)
	at java.net.ServerSocket.implAccept(ServerSocket.java:545)
	at java.net.ServerSocket.accept(ServerSocket.java:513)
	at sun.management.jmxremote.LocalRMIServerSocketFactory$1.accept(LocalRMIServerSocketFactory.java:52)
	at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.executeAcceptLoop(TCPTransport.java:405)
	at sun.rmi.transport.tcp.TCPTransport$AcceptLoop.run(TCPTransport.java:377)
	at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
	- None

"Attach Listener" #12 daemon prio=9 os_prio=31 tid=0x00007fb1db03d800 nid=0x3617 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"Thread-1" #11 prio=5 os_prio=31 tid=0x00007fb1db04e800 nid=0xa603 waiting for monitor entry [0x00007000057d2000]
   java.lang.Thread.State: BLOCKED (on object monitor)
	at com.concurrency.demo.BankTransferDemo.transfer(BankTransferDemo.java:8)
	- waiting to lock <0x000000076ab76ef0> (a com.concurrency.demo.BankAccount)
	- locked <0x000000076ab76f10> (a com.concurrency.demo.BankAccount)
	at com.concurrency.demo.BankTransferDemo.lambda$1(BankTransferDemo.java:38)
	at com.concurrency.demo.BankTransferDemo$$Lambda$2/1044036744.run(Unknown Source)
	at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
	- None

"Thread-0" #10 prio=5 os_prio=31 tid=0x00007fb1d896e000 nid=0xa703 waiting for monitor entry [0x00007000056cf000]
   java.lang.Thread.State: BLOCKED (on object monitor)
	at com.concurrency.demo.BankTransferDemo.transfer(BankTransferDemo.java:8)
	- waiting to lock <0x000000076ab76f10> (a com.concurrency.demo.BankAccount)
	- locked <0x000000076ab76ef0> (a com.concurrency.demo.BankAccount)
	at com.concurrency.demo.BankTransferDemo.lambda$0(BankTransferDemo.java:32)
	at com.concurrency.demo.BankTransferDemo$$Lambda$1/135721597.run(Unknown Source)
	at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
	- None

"Service Thread" #9 daemon prio=9 os_prio=31 tid=0x00007fb1de809000 nid=0x5503 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"C1 CompilerThread3" #8 daemon prio=9 os_prio=31 tid=0x00007fb1df80a800 nid=0x3b03 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"C2 CompilerThread2" #7 daemon prio=9 os_prio=31 tid=0x00007fb1df80a000 nid=0x3a03 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"C2 CompilerThread1" #6 daemon prio=9 os_prio=31 tid=0x00007fb1df809000 nid=0x3e03 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"C2 CompilerThread0" #5 daemon prio=9 os_prio=31 tid=0x00007fb1df008800 nid=0x3803 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"Signal Dispatcher" #4 daemon prio=9 os_prio=31 tid=0x00007fb1de808800 nid=0x4103 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
	- None

"Finalizer" #3 daemon prio=8 os_prio=31 tid=0x00007fb1d8810800 nid=0x3203 in Object.wait() [0x0000700004db1000]
   java.lang.Thread.State: WAITING (on object monitor)
	at java.lang.Object.wait(Native Method)
	- waiting on <0x000000076ab08ee0> (a java.lang.ref.ReferenceQueue$Lock)
	at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144)
	- locked <0x000000076ab08ee0> (a java.lang.ref.ReferenceQueue$Lock)
	at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:165)
	at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:216)

   Locked ownable synchronizers:
	- None

"Reference Handler" #2 daemon prio=10 os_prio=31 tid=0x00007fb1d900b000 nid=0x3103 in Object.wait() [0x0000700004cae000]
   java.lang.Thread.State: WAITING (on object monitor)
	at java.lang.Object.wait(Native Method)
	- waiting on <0x000000076ab06c00> (a java.lang.ref.Reference$Lock)
	at java.lang.Object.wait(Object.java:502)
	at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
	- locked <0x000000076ab06c00> (a java.lang.ref.Reference$Lock)
	at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

   Locked ownable synchronizers:
	- None

"main" #1 prio=5 os_prio=31 tid=0x00007fb1db809000 nid=0x1003 in Object.wait() [0x000070000408a000]
   java.lang.Thread.State: WAITING (on object monitor)
	at java.lang.Object.wait(Native Method)
	- waiting on <0x000000076ab770c0> (a java.lang.Thread)
	at java.lang.Thread.join(Thread.java:1252)
	- locked <0x000000076ab770c0> (a java.lang.Thread)
	at java.lang.Thread.join(Thread.java:1326)
	at com.concurrency.demo.BankTransferDemo.main(BankTransferDemo.java:45)

   Locked ownable synchronizers:
	- None

"VM Thread" os_prio=31 tid=0x00007fb1db821000 nid=0x4c03 runnable

"GC task thread#0 (ParallelGC)" os_prio=31 tid=0x00007fb1db809800 nid=0x1f07 runnable

"GC task thread#1 (ParallelGC)" os_prio=31 tid=0x00007fb1d8008800 nid=0x1b03 runnable

"GC task thread#2 (ParallelGC)" os_prio=31 tid=0x00007fb1db009000 nid=0x1d03 runnable

"GC task thread#3 (ParallelGC)" os_prio=31 tid=0x00007fb1db009800 nid=0x2a03 runnable

"GC task thread#4 (ParallelGC)" os_prio=31 tid=0x00007fb1db00a000 nid=0x2c03 runnable

"GC task thread#5 (ParallelGC)" os_prio=31 tid=0x00007fb1db00a800 nid=0x2d03 runnable

"GC task thread#6 (ParallelGC)" os_prio=31 tid=0x00007fb1db80a000 nid=0x5203 runnable

"GC task thread#7 (ParallelGC)" os_prio=31 tid=0x00007fb1db00b800 nid=0x5003 runnable

"GC task thread#8 (ParallelGC)" os_prio=31 tid=0x00007fb1db00c000 nid=0x4f03 runnable

"GC task thread#9 (ParallelGC)" os_prio=31 tid=0x00007fb1d900a800 nid=0x4d03 runnable

"VM Periodic Task Thread" os_prio=31 tid=0x00007fb1d8028800 nid=0xa803 waiting on condition

JNI global references: 333


Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x00007fb1db8270a8 (object 0x000000076ab76ef0, a com.concurrency.demo.BankAccount),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x00007fb1db827158 (object 0x000000076ab76f10, a com.concurrency.demo.BankAccount),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
	at com.concurrency.demo.BankTransferDemo.transfer(BankTransferDemo.java:8)
	- waiting to lock <0x000000076ab76ef0> (a com.concurrency.demo.BankAccount)
	- locked <0x000000076ab76f10> (a com.concurrency.demo.BankAccount)
	at com.concurrency.demo.BankTransferDemo.lambda$1(BankTransferDemo.java:38)
	at com.concurrency.demo.BankTransferDemo$$Lambda$2/1044036744.run(Unknown Source)
	at java.lang.Thread.run(Thread.java:748)
"Thread-0":
	at com.concurrency.demo.BankTransferDemo.transfer(BankTransferDemo.java:8)
	- waiting to lock <0x000000076ab76f10> (a com.concurrency.demo.BankAccount)
	- locked <0x000000076ab76ef0> (a com.concurrency.demo.BankAccount)
	at com.concurrency.demo.BankTransferDemo.lambda$0(BankTransferDemo.java:32)
	at com.concurrency.demo.BankTransferDemo$$Lambda$1/135721597.run(Unknown Source)
	at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.

我们从中可以看到线程的状态有RUNNABLE,WAITING,BLOCKED,例如:

"Thread-0" #10 prio=5 os_prio=31 tid=0x00007fb1d896e000 nid=0xa703 waiting for monitor entry [0x00007000056cf000]
   java.lang.Thread.State: BLOCKED (on object monitor)
	at com.concurrency.demo.BankTransferDemo.transfer(BankTransferDemo.java:8)
	- waiting to lock <0x000000076ab76f10> (a com.concurrency.demo.BankAccount)
	- locked <0x000000076ab76ef0> (a com.concurrency.demo.BankAccount)
	at com.concurrency.demo.BankTransferDemo.lambda$0(BankTransferDemo.java:32)
	at com.concurrency.demo.BankTransferDemo$$Lambda$1/135721597.run(Unknown Source)
	at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
	- None

下面是死锁的相关信息:

Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x00007fb1db8270a8 (object 0x000000076ab76ef0, a com.concurrency.demo.BankAccount),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x00007fb1db827158 (object 0x000000076ab76f10, a com.concurrency.demo.BankAccount),
  which is held by "Thread-1"

从上面的描述中,我们可以清楚的看到2个线程在互相等待对方持有的锁对象。

jstack是一个非常实用的工具,我会在后面找机会详细的说明如何使用它和其他相关工具。

posted @ 2021-01-15 21:07  李潘  阅读(186)  评论(0编辑  收藏