public class MyThread extends Thread{
@Override
public void run() {
System.out.println("running....");
}
public static void main(String[] args) throws InterruptedException {
MyThread t = new MyThread();
log(t);
t.start();
log(t);
for (int i = 0; i < 50; i++) {
log(t);
}
}
public static void log(Thread thread){
System.out.println("Thread status is: " + thread.getState());
}
}
打印的结果为:
Thread status is: NEW
Thread status is: RUNNABLE
Thread status is: RUNNABLE
Thread status is: RUNNABLE
Thread status is: RUNNABLE
Thread status is: RUNNABLE
Thread status is: BLOCKED
Thread status is: BLOCKED
running....
Thread status is: RUNNABLE
Thread status is: TERMINATED
Thread status is: TERMINATED
为什么线程启动后为经历BLOKED的状态呢?
CPU资源有限,线程运行需要占用CPU资源,目前一般线程运行都是采用抢占CPU的机制,系统给每个线程分配时间片,在某个时间片内执行某个线程。若是CPU核数少,开启的系统资源多,启动的线程就会经历Blocked状态。