一、线程的六种状态
- New
- Runnable
- Blocked
- Waiting
- Timed Waiting
- Terminated
New、Runnable、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(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//线程运行中--runnable状态
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<1000;i++){
System.out.println(i);
}
}
}
新建线程后,线程进入new状态,在运行start方法后,线程就进入runnable状态(只要start方法执行,就会变成runnable,不需要在意线程是否真正已经在cpu上执行)
Blocked、Waiting、TimedWaiting
public class BlockedWaitingTimedWaiting implements Runnable {
public static void main(String[] args) {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//TIMED_WAITING状态,因为正在执行sleep
System.out.println(thread1.getState());
//BLOCKED状态,因为线程二想要拿到线程一的锁
System.out.println(thread2.getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
//执行了wait方法
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
当线程进入runnable方法后,若遇到synchronized修饰的方法,并且没有获得锁,就会进入BLOCKED状态,再获取锁之后,进入runnable状态;若遇到了wait方法,就进入waiting状态;若存在时间参数,就进入TIMED_WAITING状态。