首先查看线程状态的方法为:Thread类对象.getState()
isAlive()方法:返回一个布尔变量,线程处于NEW和TERMINATED状态是不存活状态,返回False;反之其他的状态都是存活状态,返回True。
NEW状态:
public class Main {
public static void main(String[] args) {
Thread thread01 = new Thread(()->{
System.out.println("这是thread01线程...");
});
System.out.println(thread01.getState());
}
}
以上的代码运行结果为:NEW。表示线程thread01对象虽然已经存在,但是还未正式创建和运行起来。
RUNNABLE状态:
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread02 = new Thread(()->{
while (true){
}
});
thread02.start();
Thread.sleep(1000);
System.out.println(thread02.getState());
}
}
以上的代码运行结果为:RUNNABLE。表示线程thread02整在运行或就绪状态。
BLOCKED状态:
public class Main {
public static void main(String[] args) throws InterruptedException {
Object object = new Object();
Thread thread02 = new Thread(()->{
synchronized (object){
while (true){
}
}
});
Thread thread03 = new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (object){
while (true){
}
}
});
thread02.start();
thread03.start();
Thread.sleep(1000);
System.out.println(thread03.getState());
}
}
以上的代码运行结果为:BLOCKED。表示线程thread03由于锁竞争导致阻塞。
WAITING状态:
public class Main {
public static void main(String[] args) throws InterruptedException {
Object object = new Object();
Thread thread04 = new Thread(()->{
synchronized (object){
try {
object.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
thread04.start();
Thread.sleep(1000);
System.out.println(thread04.getState());
}
}
以上的代码运行结果为:WAITING。表示线程thread04由于wait()不固定时间导致阻塞。
TIMED_WAITING状态:
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread05 = new Thread(()->{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread05.start();
Thread.sleep(1000);
System.out.println(thread05.getState());
}
}
以上的代码运行结果为:TIMED_WAITING。表示线程thread05由于sleep()固定时间导致阻塞。
TERMINATED状态:
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread06 = new Thread(()->{
});
thread06.start();
Thread.sleep(1000);
System.out.println(thread06.getState());
}
}
以上的代码运行结果为:TERMINATED。表示线程thread06已经运行完成。