我寫了一個小例子程序來幫助自己理解線程。我有兩個類文件,如下圖所示:如何命名線程?
DoBench.java:
package benchmark;
public class DoBench {
public static void main(String[] args) {
Benchmark bmark = new Benchmark();
Thread Timer = new Thread(bmark,"worktimer"); // name doesn't work?
Timer.start();
doALotOfWork();
// Timer.finish(); // didn't work? why??
bmark.finish();
}
private static void doALotOfWork() {
for (int i=0;i<10;i++) {
System.out.println(i);
}
}
}
Benchmark.java:
package benchmark;
public class Benchmark implements Runnable {
long start = 0;
String timerName = Thread.currentThread().getName();
public void finish() {
long diff = (System.currentTimeMillis()-start);
System.err.println("\n"+timerName + " took " + diff + "ms");
}
@Override
public void run() {
start = System.currentTimeMillis();
System.err.println("\nStarted timer " + timerName);
}
}
,輸出是:
Started timer main
0
1
2
3
4
5
6
7
8
9
main took 0ms
我有兩個問題,
- 我如何給線程一個可以訪問的名字(工作者)?
- 如何訪問線程的finish()方法,而不是基準測試()?