文章目录
1 有哪6种状态?
1.1 new
已创建但还没启动的线程.
用new新建一个线程,但是还没有执行start方法,此时线程处于new的状态。
还没有开始运行,但是已经做了一些工作。
1.2 runnable
一旦又new调用了start方法 就是runnable状态了。
调用了start,不一定启动了,有可能系统没有分配资源给他,他还处于等待,这种情况下是runnable还是waiting?
runnable。是可运行的,不是运行中。
虽然他没有运行,但他是可运行的状态。随时随地可能被调度器分配cpu资源,进行运行
1.3 blocked
当一个线程被synchronize修饰。并且该锁已经被其他锁拿走了,线程的状态就是blocked。
1.4 waiting(没有时间期限)
没有设置 timed waiting参数的object.waiting()
thread.join(),
lockSupport.park()
1.5 timed waiting(有时间期限)
object.waiting(time),
thread.join(time),
lockSupport.park(time)
lockSupport.partNanos(time)
lockSupport.partUtil(time)
1.6 terminated
已终止
2代码演示状态
2.1 展示线程的NEW、RUNNABLE、Terminated状态。
package threadcoreknowledge.sixstates;
/**
* 描述: 展示线程的NEW、RUNNABLE、Terminated状态。即使是正在运行,也是Runnable状态,而不是Running。
*/
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();
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(100);
} 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);
}
}
}
2.2 展示Blocked, Waiting, TimedWaiting
package threadcoreknowledge.sixstates;
/**
* 描述: 展示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(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出Timed_Waiting状态,因为正在执行Thread.sleep(1000);
System.out.println(thread1.getState());
//打印出BLOCKED状态,因为thread2想拿得到sync()的锁却拿不到
System.out.println(thread2.getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
//打印出WAITING状态,因为执行了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();
}
}
}
3 阻塞状态
把 blocked(被阻塞),waiting(等待),timed_waiting(即时等待) 都称为阻塞状态
4 线程有哪些状态?生命周期是什么?
如上