下面的代碼展示了在一個方法中,通過匿名內部類定義一個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)