[小练习] 理解Thread状态

class ThreadState implements Runnable {
     public synchronized void waitForAMoment() throws InterruptedException {
         wait(500); // wait不会持有锁
     }
     
     public synchronized void waitForever() throws InterruptedException {
         wait(); // 当前线程永久等待,只能等到其他线程调用notify()或notifyAll()方法才能唤醒
     }
     
     public synchronized void nofifyNow() throws InterruptedException {
         notify();
     }
     @Override
     public void run() {
         try {
             this.waitForAMoment();
             this.waitForever();    
             System.out.println("other***" + Thread.currentThread().getState()); // other***RUNNABLE
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
     }
}
public class Test {
     public static void main(String[] args) throws InterruptedException {
         ThreadState ts = new ThreadState();
         Thread thread = new Thread(ts);
         System.out.println("创建新线程:" + thread.getState()); // 创建新线程:NEW
         thread.start();
         System.out.println("启动线程:" + thread.getState()); // 启动线程:RUNNABLE
         Thread.sleep(100);
         System.out.println("等待500ms:" + thread.getState()); // 等待500ms:TIMED_WAITING
         Thread.sleep(1000); 
         System.out.println("一直等待:" + thread.getState()); // 一直等待:WAITING
         ts.nofifyNow();
         System.out.println("唤醒进程:" + thread.getState()); // 唤醒进程:BLOCKED
         Thread.sleep(1000); // 新进程被唤醒后,继续向下执行System.out.println("other***" + Thread.currentThread().getState()),此时新线程转为Runnable状态
         System.out.println("main***" + Thread.currentThread().getState()); // main***RUNNABLE
         System.out.println("进程完结:" + thread.getState()); // 进程完结:TERMINATED
     }
}

你可能感兴趣的:([小练习] 理解Thread状态)