线程作为操作系统调度的最小单元,并且能够让多线程同时执行,极大的提高 了程序的性能,在多核环境下的优势更加明显。
Java 线程既然能够创建,那么也势必会被销毁,所以线程是存在生命周期的, 那么我们接下来从线程的生命周期开始去了解线程。 线程一共有 6 种状态(NEW、RUNNABLE、BLOCKED、WAITING、 TIME_WAITING、TERMINATED)
NEW:初始状态,线程被构建,但是还没有调用 start 方法
RUNNABLED:运行状态,JAVA 线程把操作系统中的就绪和运行两种状态统一 称为“运行中”
BLOCKED:阻塞状态,表示线程进入等待状态,也就是线程因为某种原因放弃 了 CPU 使用权,阻塞也分为几种情况
Ø 等待阻塞:运行的线程执行 wait 方法,jvm 会把当前线程放入到等待队列
Ø 同步阻塞:运行的线程在获取对象的同步锁时,若该同步锁被其他线程锁占 用了,那么 jvm 会把当前的线程放入到锁池中
Ø 其他阻塞:运行的线程执行 Thread.sleep 或者 t.join 方法,或者发出了 I/O 请求时,JVM 会把当前线程设置为阻塞状态,当 sleep 结束、join 线程终止、 io 处理完毕则线程恢复
TIME_WAITING:超时等待状态,超时以后自动返回
TERMINATED:终止状态,表示当前线程执行完毕

package com.example.demo.morethread;
import java.util.concurrent.TimeUnit;
public class ThreadStatus {
public static void main(String[] args) {
//TIME_WAITING
new Thread(()->{
while (true){
try {
System.out.println("timewaiting:before");
TimeUnit.SECONDS.sleep(100);
System.out.println("timewaiting:after");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"timewaiting").start();
//WAITING,线程在 ThreadStatus 类锁上通过 wait 进行等待
new Thread(()->{
while (true){
synchronized (ThreadStatus.class){
try {
System.out.println("wait:before");
ThreadStatus.class.wait();
System.out.println("wait:after");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"waiting").start();
//线程在 ThreadStatus 加锁后,不会释放锁
new Thread(new BlockedDemo(),"demo1").start();
new Thread(new BlockedDemo(),"demo2").start();
}
static class BlockedDemo extends Thread{
@Override
public void run() {
synchronized (BlockedDemo.class){
while (true){
try {
System.out.println(Thread.currentThread().getName()+":before");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+":after");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
运行结果如下:
2250

被折叠的 条评论
为什么被折叠?



