Java线程有五个状态:就绪(刚创建的时候),运行中(RUNNING),限时等待中(TIMED_WAITING),等待中(WAITING),阻塞(BLOCKED)
以下代码模拟线程的各个情况(针对TIMED_WAITING,WAITING和BLOCKED)
public class ThreadStatusDemo {
public static void main(String[] args) throws Exception{
Thread waitDemoThread1 = new Thread(new WaitDemo1());
Thread sleepDemoThread = new Thread(new SleepDemo());
// waiting状态
waitDemoThread1.start();
// timed_waiting状态
sleepDemoThread.start();
// blocked状态
new Thread(new BlockDemo()).start();
// notify和waiting状态
new Thread(new WaitDemo2()).start();
// timed_waiting状态
sleepDemoThread.join(600000);
}
static class WaitDemo1 implements Runnable{
@Override
public void run() {
Thread.currentThread().setName("WaitDemo1");
synchronized (WaitDemo1.class) {
try {
WaitDemo1.class.wait();
System.out.println("WaitDemo1");
WaitDemo1.class.wait();
System.out.println("WaitDemo1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class WaitDemo2 implements Runnable{
@Override
public void run() {
Thread.currentThread().setName("WaitDemo2");
while (true) {
synchronized (WaitDemo1.class) {
WaitDemo1.class.notifyAll();
}
synchronized (WaitDemo1.class) {
try {
WaitDemo1.class.wait();
System.out.println("WaitDemo2");
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
}
}
static class SleepDemo implements Runnable{
@Override
public void run() {
Thread.currentThread().setName("SleepDemo");
synchronized (SleepDemo.class) {
try {
while (true) {
Thread.currentThread().sleep(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class BlockDemo implements Runnable{
@Override
public void run() {
Thread.currentThread().setName("BlockDemo");
synchronized (SleepDemo.class) {
}
}
}
}
查看线程状态可以使用jstack工具,操作步骤:
1、在项目目录下的终端输入jps回车,找到本程序的进程号,本例中是15412
2、在终端中再输入jstack 15412 回车,得到各个线程的运行状态