下面的程式碼展示了在一個方法中,透過匿名內部類別定義一個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)
Th.1
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-3 run 2 time(s)
time(s)Thread-4 run 2 time(s)