线程的六种状态
New:初始状态 (未调用start )刚刚创建完
Runnable:运行状态 执行start
Blocked:阻塞状态
Waiting:等待状态 通过Join sleep等方法使线程在等待
Timed Waiting :计时等待状态 sleep join 等方法设置了参数
Terminated:终止状态,线程执行完毕
package org.example.test1; public class StateThread { public static void test1(){//NEW Thread t1 = new Thread(()->{ System.out.println("Thread1"); }); System.out.println(t1.getState()); } public static void test2() throws InterruptedException {//Terminated Thread t1 = new Thread(()->{ System.out.println("线程开始执行"); System.out.println("线程结束执行"); }); t1.start(); Thread.sleep(3000); System.out.println(t1.getState()); } public static void test3(){//Runnable Thread t1 = new Thread(()->{ }); t1.start(); System.out.println(t1.getState()); } public static void test4() throws InterruptedException {//Blocked class Table{ public synchronized void use(){ System.out.println(Thread.currentThread().getName()+"-使用桌子"); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Thread.currentThread().getName()+"-使用完毕"); } } System.out.println(Thread.currentThread().getName()); Table table = new Table(); Thread student1 = new Thread(()->{ table.use(); },"s1"); Thread student2 = new Thread(()->{ table.use(); },"s2"); student1.start(); Thread.sleep(1000); student2.start(); Thread.sleep(1000); System.out.println(student2.getState()); } public static void test5() throws InterruptedException {//Waiting class Table{ public synchronized void use() throws InterruptedException { System.out.println(Thread.currentThread().getName()+"-使用桌子"); System.out.println("忘记点餐了"); wait(); System.out.println(Thread.currentThread().getName()+"-使用完毕"); } } Table table = new Table(); Thread student1 = new Thread(()->{ try { table.use(); } catch (InterruptedException e) { throw new RuntimeException(e); } },"s1"); student1.start(); Thread.sleep(100); System.out.println(student1.getState()); } public static void test6() throws InterruptedException {//Timed_Waiting class Table{ public synchronized void use() throws InterruptedException { System.out.println(Thread.currentThread().getName()+"-使用桌子"); System.out.println("忘记点餐了"); wait(3000); System.out.println(Thread.currentThread().getName()+"-使用完毕"); } } Table table = new Table(); Thread student1 = new Thread(()->{ try { table.use(); } catch (InterruptedException e) { throw new RuntimeException(e); } },"s1"); student1.start(); Thread.sleep(100); System.out.println(student1.getState()); } public static void main(String[] args) throws InterruptedException { //test1(); //test2(); //test3(); //test4(); //test5(); test6(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端