1 每个状态的含义
New
,线程已经创建,但是还没有启动Runnable,可运行的,不是运行中的
,一旦调用 start
方法,线程就会进入 Runnable
状态。也就是说从New
到 Runnable
,不会从 New
到 Waiting
。java 的Runnable
对应操作系统的 Ready
和 Running
Blocked
,当一个线程进入到被 synchronized
修饰的代码块的时候,并且该锁已经被其他线程拿走了,此时线程状态就是 Blocked
Waiting
,(1)没有设置timeout的Object.wait()
方法,
public class NewRunnableTerminated implements Runnable{
public static void main(String[] args) {
final Thread thread = new Thread(new NewRunnableTerminated());
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
public class BlockedWaitingTimedWaiting implements Runnable {
public static void main(String[] args) {
final BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
final Thread thread1 = new Thread(runnable);
thread1.start();
final Thread thread2 = new Thread(runnable);
thread2.start();
System.out.println("线程1:" + thread1.getState());
System.out.println("线程2:" + thread2.getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程1:" + thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(1000);
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2 阻塞状态
- 一般,把
Blocked
,Waiting
,Timedwaiting(计时等待)
都称为阻塞状态; - 不仅仅是 Blocked
3 常见面试问题
- 线程有哪几种状态?生命周期是什么?
见上图