Java:使用匿名內部類在方法內部定義並啟動線程

來源:互聯網
上載者:User

下面的代碼展示了在一個方法中,通過匿名內部類定義一個Thread,並Override它的run()方法,之後直接啟動該線程。

這樣的代碼可用於在一個類內部通過另起線程來執行一個支線任務,一般這樣的任務並不是該類的主要設計內容。

package com.zj.concurrency;

public class StartFromMethod {
  private Thread t;
  private int number;
  private int count = 1;
  public StartFromMethod(int number) {
    this.number = number;
  }
  public void runTask() {
    if (t == null) {
      t = new Thread() {
       public void run() {
         while (true) {
           System.out.println("Thread-" + number + " run " + count
              + " time(s)");
           if (++count == 3)
             return;
         }
       }
      };
      t.start();
    }
  }
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++)
      new StartFromMethod(i).runTask();
  }
}

結果:

Thread-0 run 1 time(s)
Thread-0 run 2 time(s)
Thread-1 run 1 time(s)
Thread-1 run 2 time(s)
Thread-2 run 1 time(s)
Thread-2 run 2 time(s)
Thread-3 run 1 time(s)
Thread-3 run 2 time(s)
Thread-4 run 1 time(s)
Thread-4 run 2 time(s)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.