天天看點

java建立多線程的幾種方式

提示

需要注意的是,無論用何種方式建立啟動線程,都要給它一個名字,這對排錯診斷系統監控有幫助,否則診斷問題時,無法直覺知道某個線程的用途.

繼承Thread類

MyThread類

public class MyThread extends Thread {
  public MyThread() {
  }

  //private String name;
  MyThread(String name) {
    //this.name = name;
    super(name);
  }

  @Override
  public void run() {
    for (int i = 0; i < 20; i++) {
      /**
       * Thread.currentThread() 傳回目前線程的引用
       * this.getName()  傳回目前線程的名字 外部方法怎麼setName設定線程名字,内部就可以擷取線程名字
       */
      System.out.println(this.getName() + " : " + i);

    }
  }
}      
public class Main {
  /**
   * 繼承方式實作線程
   *
   * @param args
   */
  public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.setName("我是main線程");
    myThread.run();
  }
}      

實作Runnable接口

public class MyTask implements Runnable {

  @Override
  public void run() {
    for (int i = 0; i < 20; i++) {
      //擷取線程名字
      System.out.println(Thread.currentThread().getName()+i);
    }
  }
}      
public class Main {
  /**
   * 實作方式建立線程
   */
  public static void main(String[] args) {
    MyTask myTask = new MyTask();
    Thread thread = new Thread(myTask);
    thread.setName("Runnable");// 設定名字
    String name = thread.getName(); //擷取名字
    boolean interrupted = thread.isInterrupted();//如果這個線程被中斷就傳回true
//    thread.checkAccess();
    ClassLoader contextClassLoader = thread.getContextClassLoader();//傳回此線程的上下文類加載器
    long id = thread.getId();//傳回此線程的辨別符
    int priority = thread.getPriority();//傳回線程的優先級

    Thread.State state = thread.getState(); //傳回線程的狀态 , 具體的點State枚舉看源碼
    ThreadGroup threadGroup = thread.getThreadGroup();//傳回線程組

    boolean alive = thread.isAlive(); //測試線程是否活動
    boolean daemon = thread.isDaemon(); //測試線程是否是守護線程

    thread.start();

  }
}      

匿名内部類方式建立

/**
 * 匿名内部類方式建立
 */
public class Main {

  public static void main(String[] args) {

    //1.第一種方式 繼承方式
    new Thread() {
      @Override
      public void run() {
        //任務代碼
        for (int i = 0; i < 20; i++) {
          System.out.println(Thread.currentThread().getName() + ":" + i);
        }
      }
    }.start();

//2.第二種方式 實作方法
    new Thread(new Runnable() {
      @Override
      public void run() {
        for (int i = 0; i < 20; i++) {
          System.out.println(Thread.currentThread().getName() + ":" + i);
        }
      }
    }).start();

    //主線程代碼
    for (int i = 0; i < 20; i++) {
      System.out.println(Thread.currentThread().getName() + ":" + i);
    }
  }
}