el-table卡到爆?试试这招:虚拟滚动原理与umy-ui u-table深度配置指南
2026/5/28 10:29:11
在 Java 中,线程的状态是由 Thread.State 枚举定义的,一共有 6 种状态。这些状态代表了线程从创建到销毁的各个阶段。我们可以通过 Thread.getState() 方法来获取当前线程的状态。
以下是所有线程状态的列表:
状态转移的意义:
观察 1:关注 NEW 、 RUNNABLE 、 TERMINATED 状态的转换
public class Observation1 { public static void main(String[] args) throws InterruptedException { // 创建线程 (NEW 状态) Thread simpleThread = new Thread(() -> { System.out.println("Thread is running... Doing some work."); // 模拟工作,结束后自然进入 TERMINATED }); // 观察 NEW 状态 System.out.println("State after creation: " + simpleThread.getState()); // NEW // 启动线程 (NEW -> RUNNABLE) simpleThread.start(); Thread.sleep(100); // 短暂等待,确保线程进入 RUNNABLE System.out.println("State after start: " + simpleThread.getState()); // RUNNABLE // 等待线程结束 (RUNNABLE -> TERMINATED) simpleThread.join(); System.out.println("State after termination: " + simpleThread.getState()); // TERMINATED } }观察 2:关注 WAITING 、 BLOCKED 、 TIMED_WAITING 状态的转换
public class Observation2 { private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { // 创建工作者线程 Thread workerThread = new Thread(() -> { try { // 进入 TIMED_WAITING (sleep) System.out.println("Entering TIMED_WAITING via sleep..."); Thread.sleep(1000); // 进入 WAITING (wait) synchronized (lock) { System.out.println("Entering WAITING via wait..."); lock.wait(); } // 模拟工作结束 System.out.println("Worker thread resuming after notify."); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); // 创建阻塞模拟线程:先占用锁 Thread blockerThread = new Thread(() -> { synchronized (lock) { try { System.out.println("Blocker holding lock for 2 seconds..."); Thread.sleep(2000); // 占用锁,迫使其他线程 BLOCKED } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); // 启动 blocker 先占用锁 blockerThread.start(); Thread.sleep(100); // 确保 blocker 先运行 // 启动 worker (进入 RUNNABLE) workerThread.start(); Thread.sleep(100); System.out.println("Worker state after start: " + workerThread.getState()); // RUNNABLE // 观察 TIMED_WAITING (sleep) Thread.sleep(500); System.out.println("Worker state during sleep: " + workerThread.getState()); // TIMED_WAITING // 等待 sleep 结束,worker 尝试 wait,但需先获取锁(可能 BLOCKED) Thread.sleep(1000); System.out.println("Worker state when trying to acquire lock for wait: " + workerThread.getState()); // BLOCKED (如果 blocker 还在占用) // 等待 blocker 释放锁,worker 进入 WAITING Thread.sleep(1500); System.out.println("Worker state during wait: " + workerThread.getState()); // WAITING // 唤醒 worker (WAITING -> RUNNABLE) synchronized (lock) { lock.notify(); } Thread.sleep(100); System.out.println("Worker state after notify: " + workerThread.getState()); // RUNNABLE 或 TERMINATED // 等待结束 workerThread.join(); blockerThread.join(); } }