New 已创建但还未启动
Runnable 一旦调用start之后就是runnable(可运行) 对应了ready和running cpu在分配中也是runnable
Blocked 锁 进入synchronized修饰的代码块
Waiting
Timed Waiting
Terminated
public class NewRunnableTerminated implements Runnable{
public static void main(String[] args) {
Thread thread = new Thread(new NewRunnableTerminated());
//NEW状态
System.out.println(thread.getState());
thread.start();
//Runnable状态
System.out.println(thread.getState());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Runnable状态,即使是正在运行,也是Runnable状态,而不是Running
System.out.println(thread.getState());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Terminated
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i <10000 ; i++) {
System.out.println(i);
}
}
}
public class BlockedWaitingTimedWaiting implements Runnable{
public static void main(String[] args) throws InterruptedException {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread.sleep(10);
Thread thread2 = new Thread(runnable);
thread2.start();
//Time Waiting 因为正在执行的Thread.sleep(1000)
System.out.println("线程1的状态:"+thread1.getState());
//Blocked 因为thread2想得到syn()的锁 却拿不到 因为线程1没有释放
System.out.println("线程2的状态:"+thread2.getState());
Thread.sleep(1500);
//打印出Waiting
System.out.println("线程1的状态:"+thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn(){
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}