一、java的几种状态
1.NEW
Thread对象创建好了,但还没有执行start()方法。
2.TERMINATEN
Thread对象存在,但是内部线程已经执行完毕。
3.Runnable
就绪状态,(表示,正在在CPU上执行,或者准备就绪随时可以去CPU上执行)
4.TIMD_WAITING
指定时间阻塞
5.WAITING
死等
6.BLOCKED
由于锁竞争,引起的阻塞。
二、代码展示
public class ThreadTest7 {
static Thread thread1;
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
for (int i = 0; i < 1; i++) {
try {
Thread.sleep(200);
//指定时间阻塞 TIMED_WAITING
System.out.println(thread1.getState()+" thread");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// System.out.println(i +" ");
}
});
thread1=thread.currentThread();
//NEW 有线程对象,但是还有start()
System.out.println(thread.getState());
thread.start();
//RUNNABLE 正在执行,或者在准备就绪随时可以在CPU上执行
System.out.println(thread.getState());
Thread.sleep(1000);
//执行完毕,但thread 对象存在
System.out.println(thread.getState());
}
}
代码结果:
BLOCKED:
public class ThreadTest8 {
public static void main(String[] args) {
Object locker=new Object();
Object locker1=new Object();
Thread thread =new Thread(()->{
synchronized (locker){
System.out.println("thread");
synchronized (locker1){
System.out.println("thread 你好:");
}
}
});
Thread thread1 =new Thread(()->{
synchronized (locker1){
System.out.println("thread1");
synchronized (locker){
System.out.println("thread1 : 你好");
}
}
});
thread1.start();
thread.start();
System.out.println(thread1.getState());//RUNNABLE
System.out.println(thread.getState());//BLOCKED
}
}
执行结果:
上述展示了线程的五种状态,查看jconsole都可以观察到,waiting后序文章将介绍到。