线程的六种状态
线程一共有六种状态,分为 new、runnable、blocked、waiting、Timed waiting、terminated。
new状态
Thread thread = new Thread(new SleepInterrupted());
当前就处在new状态
Runnable状态
thread.start();
这时进入Runnable状态(Runnable状态既有等待执行的时候也有正在执行的时候)
Blocked、Waiting、Timed_Waiting状态
public class BLockedWaitingTimedWating implements Runnable{
public static void main(String[] args) {
BLockedWaitingTimedWating runnable = new BLockedWaitingTimedWating();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread1.getState());
System.out.println(thread2 .getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn(){
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果
TIMED_WAITING
BLOCKED
WAITING
当两个线程竞争同一把锁,一个线程需要等待另一个线程释放锁时,此时这个线程的状态是blocked状态。当线程调用了类似wait()
方法时,此时线程状态是waiting状态。当线程调用了类似Thread.sleep(2000)
这样的方法时,此时线程的状态是Timed waiting状态。
Terminated状态
当线程运行结束或者意外终止,此时线程进入terminated状态。