我编写了一个小示例程序来帮助自己理解线程。我有两个类文件,如下:
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);
}
}
}
基准.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
我有两个问题,
- 如何给线程一个可以访问的名称(工作计时器)?
- 如何访问 Thread 的 finish() 方法,而不是 Benchmark() 的?