线程的六种状态
1.NEW
新创建的线程,尚未启动,此时线程对象已经创建,还未使用
start
方法
2.RUNNABLE
可执行状态,可分为正在执行和即将执行,已经使用
start
方法
等待CPU分配资源,当资源可用时,线程会被调度并执行
3.BLOCKED
阻塞状态,线程在等待某个条件满足(如锁、IO操作完成等)才能继续执行
如阻塞在被synchronized
关键字修饰的方法或者代码块
4.WAITING
等待状态,线程主动放弃CPU资源,进入等待队列,等待其他线程发送信号或唤醒,不会自动唤醒
如使用无参的join
方法
5.TIMED_WAITING
超时等待,与上面的等待状态类似,不过在超过一定时间会自动唤醒
如带有参数的join
方法,sleep
方法
6. TERMINATED
终止状态,线程的
run
方法执行完毕或者主线程结束,线程就结束了,线程一但终止就不能复生
如果重新start
终止的线程,会抛出IllegalThreadStateException
异常
状态之间的切换
1. NEW -> RUNNABLE
使用
start
方法
2. RUNNABLE -> TERMINATED
线程的
run
方法执行完毕或者主线程结束
3. RUNNABLE -> BLOCKED
就像下面代码 t2就是BLOCKED
状态
public static void main(String[] args) {
Object object=new Object();
Thread t1 =new Thread(()->{
synchronized (object) {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t1");
}
}
});
t1.start();
Thread t2=new Thread(()->{
synchronized (object) {
System.out.println("t2");
}
});
t2.start();
}
4.RUNNABLE -> WAITING /TIMED_WAITING
下面结果分别是10000和0,第一个是等待到唤醒,第二个是到一定时间自动唤醒
public class TestDemo2 {
static int count=0;
public static void main(String[] args) throws InterruptedException {
Thread t2=new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 10000; i++) {
count++;
}
});
t2.start();
t2.join();
System.out.println(count);
}
}
public class TestDemo2 {
static int count=0;
public static void main(String[] args) throws InterruptedException {
Thread t2=new Thread(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 10000; i++) {
count++;
}
});
t2.start();
t2.join(500);
System.out.println(count);
}
}