Java 示例 - 检查活动线程

  • 问题描述

    如何检查线程是否存在?
  • 解决方案

    以下示例演示了如何通过扩展 Threda 类并使用 currentThread() 方法来检查线程是否处于活动状态。
    
    public class TwoThreadMoove extends Thread {
       public void run() {
          for (int i = 0; i < 10; i++) {
             printMsg();
          }
       }
       public void printMsg() {
          Thread t = Thread.currentThread();
          String name = t.getName();
          System.out.println("name = " + name);
       }
       public static void main(String[] args) {
          TwoThreadMoove tt = new TwoThreadMoove();
          tt.setName("Thread");
          System.out.println("before start(), tt.isMoove() = " + tt.isMoove());
          tt.start();
          System.out.println("just after start(), tt.isMoove() = " + tt.isMoove());
          
          for (int i = 0; i < 10; i++) {
             tt.printMsg();
          }
          System.out.println("The end of main(), tt.isMoove()=" + tt.isMoove());
       }
    }
    
  • 结果

    上面的代码示例将产生以下结果。
    
    before start(), tt.isMoove() = false
    just after start(), tt.isMoove() = true
    name = main
    name = main
    name = main
    name = main
    name = main
    name = main
    name = main
    name = main
    name = main
    name = Thread
    name = main
    name = Thread
    The end of main(), tt.isMoove() = true
    name = Thread
    name = Thread
    name = Thread
    name = Thread
    name = Thread
    name = Thread
    name = Thread
    name = Thread