查看运行时的线程信息

  1. 打开终端
  2. 输入命令jps, 结果示例:

35696 KotlinCompileDaemon
7812 Launcher
11880 ThreadState
14408
21064 Jps

  1. 输入命令jstack #pid#, 这里是jstack 11880, 结果示例:

“BlockedThread-2” #12 prio=5 os_prio=0 tid=0x151af800 nid=0x50dc waiting for monitor entry [0x1568f000]
java.lang.Thread.State: BLOCKED (on object monitor)

“BlockedThread-1” #11 prio=5 os_prio=0 tid=0x151ab400 nid=0x5b64 waiting on condition [0x155ff000]
java.lang.Thread.State: TIMED_WAITING (sleeping)

“WaitingThread” #10 prio=5 os_prio=0 tid=0x151a6400 nid=0x8858 in Object.wait() [0x1556f000]
java.lang.Thread.State: WAITING (on object monitor)

“TimeWaitingThread” #9 prio=5 os_prio=0 tid=0x151a5c00 nid=0x5878 waiting on condition [0x154df000]
java.lang.Thread.State: TIMED_WAITING (sleeping)

代码

public class SleepUtils {
	public static void second(Long seconds) {
		try {
			TimeUnit.SECONDS.sleep(seconds);
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}
	}
}
public class ThreadState {

	public static void main(String[] args) {
		new Thread(new TimeWaiting(), "TimeWaitingThread").start();
		new Thread(new Waiting(), "WaitingThread").start();
		// 使用两个Blocked线程, 一个取锁成功, 另一个被阻塞
		new Thread(new Blocked(), "BlockedThread-1").start();
		new Thread(new Blocked(), "BlockedThread-2").start();
	}

	// 该线程不断的进行睡眠
	static class TimeWaiting implements Runnable {
		@Override
		public void run() {
			while (true) {
				SleepUtils.second(100L);
			}
		}
	}

	// 该线程在Waiting.class实例上等待
	static class Waiting implements Runnable {
		@Override
		public void run() {
			while (true) {
				synchronized (Waiting.class) {
					try {
						Waiting.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
						Thread.currentThread().interrupt();
					}
				}
			}
		}
	}

	//改下线程在Blocked.class实例上加锁后, 不会释放该锁
	static class Blocked implements Runnable {
		@Override
		public void run() {
			synchronized (Blocked.class) {
				while (true) {
					SleepUtils.second(100L);
				}
			}
		}
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值