2013-07-06 22 views
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); 
      } 
    } 
} 

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 

我有兩個問題,

  1. 我如何給線程一個可以訪問的名字(工作者)?
  2. 如何訪問線程的finish()方法,而不是基準測試()?

回答

2

getName()被調用的上下文是錯誤的。

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

原因:當上述代碼執行時,在上下文中的Thread主線程。由於上面的代碼屬於你Runnable實施初始化塊,由於在main()要初始化的Thread,通過傳遞這個Runnable,該主線程執行的Benchmark初始化塊。

所以timerNamerun()方法獲取主線程

呼叫getName()的價值像下面

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

我怎麼可以給線程的名稱,它可以訪問(worktimer)?

timer.getName() 

如何訪問線程的結束()方法,而不是基準的()?

沒有對Thread

1

方法finish()實際的問題是

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內。