线程状态

230 阅读2分钟
  1. 线程状态
    public enum State {
        // 新建
        // Thread state for a thread which has not yet started.
        NEW,
        
        // 运行,或者等待系统资源
        // Thread state for a runnable thread. 
        // A thread in the runnable state is executing in the Java virtual machine
        // but it may be waiting for other resources from the operating system such
        // as processor.
        RUNNABLE,
        
        // 阻塞,被monitor lock(synchronized)阻塞
        // Thread state for a thread blocked waiting for a monitor lock.
        // A thread in the blocked state is waiting for a monitor lock to enter a
        // synchronized block/method or reenter a synchronized block/method after
        // calling Object.wait.
        BLOCKED,
        
        // 等待,Object.wait,Thread.join,或者LockSupport.park
        // Thread state for a waiting thread. A thread is in the waiting state due
        // to calling one of the following methods:       
        // Object.wait with no timeout
        // Thread.join with no timeout
        // LockSupport.park
        // A thread in the waiting state is waiting for another thread to perform
        // a particular action. For example, a thread that has called Object.wait()
        // on an object is waiting for another thread to call Object.notify() or
        // Object.notifyAll() on that object. A thread that has called Thread.join()
        // is waiting for a specified thread to terminate.
        WAITING,
        
        // 超时等待
        // Thread state for a waiting thread with a specified waiting time. A thread
        // is in the timed waiting state due to calling one of the following methods
        // with a specified positive waiting time:
        // Thread.sleep
        // Object.wait with timeout
        // Thread.join with timeout
        // LockSupport.parkNanos
        // LockSupport.parkUntil
        TIMED_WAITING,
        
        // 结束
        // Thread state for a terminated thread. The thread has completed execution.
        TERMINATED;
    }
    
  2. NEW新建
    @Test
    void testNewState() {
        Thread t = new Thread(() -> System.out.println("do something"));
        assertEquals(Thread.State.NEW, t.getState());
    }
    
  3. RUNNABLE运行
    @Test
    void testRunnableState() {
        Thread t = new Thread(() -> {
            long startTime = System.currentTimeMillis();
            while (System.currentTimeMillis() - startTime < 3_000L) {
            }
        });
    
        t.start();
    
        assertEquals(Thread.State.RUNNABLE, t.getState());
    }
    
  4. TERMINATED结束
    @Test
    void testTerminatedState() throws InterruptedException {
        Thread t = new Thread(() -> {
            System.out.println("do something");
        });
    
        t.start();
        t.join();
        
        assertEquals(Thread.State.TERMINATED, t.getState());
    }
    
  5. BLOCKED阻塞
    获取object monitor时被阻塞
    @Test
    void testBlockedByGettingObjectMonitor() throws InterruptedException {
        final Object mutex = new Object();
    
        Runnable runnable = () -> {
            synchronized (mutex) {
                try {
                    Thread.sleep(5_000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
    
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
    
        t1.start();
        t2.start();
    
        // Make sure t1 and t2 have started.
        Thread.sleep(2_000L);
    
        // T2 is blocked by object monitor
        assertEquals(Thread.State.BLOCKED, t2.getState());
    }
    
  6. WAITING等待
    • 调用object.wait()后
      @Test
      void testWaitingForSignal() throws InterruptedException {
          final Object mutex = new Object();
          Thread t1 = new Thread(() -> {
              synchronized (mutex) {
                  try {
                      mutex.wait();
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }
          });
      
          t1.start();
      
          Thread.sleep(1_000L);
      
          assertEquals(Thread.State.WAITING, t1.getState());
      }
      
    • 获取lock
      @Test
      void testWaitingForGetLock() throws InterruptedException {
          Lock lock = new ReentrantLock();
      
          Thread t1 = new Thread(() -> {
              lock.lock();
              try {
                  Thread.sleep(10_000L);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } finally {
                  lock.unlock();
              }
          });
      
          Thread t2 = new Thread(() -> {
              lock.lock();
              try {
                  System.out.println("do something");
              } finally {
                  lock.unlock();
              }
          });
      
          t1.start();
          t2.start();
      
          Thread.sleep(2_000L);
      
          assertEquals(Thread.State.WAITING, t2.getState());
      }
      
    • 等待Condition
      @Test
      void testWaitingForCondition() throws InterruptedException {
          final Lock lock = new ReentrantLock();
          Condition condition = lock.newCondition();
      
          Thread t1 = new Thread(() -> {
              lock.lock();
              try {
                  condition.await();
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } finally {
                  lock.unlock();
              }
          });
      
          t1.start();
      
          Thread.sleep(2_000L);
      
          assertEquals(Thread.State.WAITING, t1.getState());
      }