- 打开终端
- 输入命令
jps, 结果示例:
35696 KotlinCompileDaemon
7812 Launcher
11880 ThreadState
14408
21064 Jps
- 输入命令
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);
}
}
}
}
}

本文通过实例演示了Java中各种线程状态的实际表现,包括运行、阻塞、等待和超时等待等,深入剖析了线程在不同状态下的行为特征,并提供了具体的代码实现。

被折叠的 条评论
为什么被折叠?



