0

我编写了一个小示例程序来帮助自己理解线程。我有两个类文件,如下:

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

我有两个问题,

  1. 如何给线程一个可以访问的名称(工作计时器)?
  2. 如何访问 Thread 的 finish() 方法,而不是 Benchmark() 的?
4

3 回答 3

2

被调用的上下文getName()是错误的。

String timerName = Thread.currentThread().getName(); 

原因:当上面的代码执行时,Thread上下文将是主线程。由于上面的代码属于您的实现的初始化块Runnable,并且由于main()您正在初始化Thread,通过传递 this Runnable主线程执行 的初始化块Benchmark

所以timerName获取主线程的值

getName()run()如下方法调用

@Override
public void run() {
    start = System.currentTimeMillis();
    System.err.println("\nStarted timer " + Thread.currentThread().getName());
}
于 2013-07-06T18:06:22.280 回答
2

如何给线程一个可以访问的名称(工作计时器)?

timer.getName()

如何访问 Thread 的 finish() 方法,而不是 Benchmark() 的?

没有finish()办法Thread

于 2013-07-06T18:06:29.397 回答
1

实际问题是

String timerName = Thread.currentThread().getName();

它在实例化时设置计时器名称,它是main实例化此可运行对象的线程

Benchmark bmark = new Benchmark(); // currentThread() is main here

因此,要解决此问题,请确定您的currentThread()内部run()

@Override
public void run() {
    start = System.currentTimeMillis();
    System.err.println("\nStarted timer " + Thread.currentThread().getName());
}

另外,请注意,因为它始终main是调用的线程

bmark.finish();

它会一直打印main

于 2013-07-06T18:07:38.163 回答