2012-08-07 71 views
1

如何在這種情況下爲父母和孩子設置同名如何從父級獲取線程名稱?

public class ComponentA { 
    public static void main(String[] args){ 

     Bye bye = new Bye(); 
     Thread t = new Thread(bye); 
     t.start(); 
    } 
} 

我不能添加t.setName(Thread.currentThread().getName());,因爲我需要避免更改代碼。我正在尋找可以從AspectJ類申請的解決方案。 有什麼方法可以將方法的參數置入run?或者,也許在子線程中,我們可以得到parent name

編輯:

我的意思是:

  • 母公司 - 主要在ComponentA
  • 孩子 - 在再見
+0

你所說的 「父」 與 「子」 是什麼意思?你是否將'Bye'(它必須位於包含'Runnable'的繼承樹)作爲子對象並將'Thread'對象't'作爲父對象? – 2012-08-07 13:56:15

+0

什麼是父母?什麼名字?你想從啓動的線程('t')獲取主線程的名字嗎? – 2012-08-07 13:56:17

+0

相關:http://stackoverflow.com/questions/11722749/how-to-find-the-name-of-the-parent-thread – Gray 2012-08-07 13:56:59

回答

4

編輯運行:

有什麼辦法可以把參數運行方法嗎?或者也許在子線程中,我們可以得到父母的名字?

一旦線程已經開始,run()方法被調用,有沒有辦法找出父線程的名稱作爲這個答案在這裏討論:

How to find the name of the parent thread?

你當然可以這樣做:

Bye bye = new Bye(); 
Thread t = new Thread(bye, Thread.currentThread().getName() + "-child"); 
t.start(); 

氏s將新創建的線程的名稱設置爲與當前線程相關的父線程。但是通過你所做的編輯,我發現你不能改變這個線程的分支。

正如在我的其他答案中提到的,我認爲你將不得不使用除名稱之外的其他機制來對線程進行分組。

run()方法的內部,您當然可以進行調用以將當前線程添加到某些線程集合中以用於報告目的。

+1

+1你可以改變Java認爲線程的名字(出現在線程中轉儲) – 2012-08-07 14:02:41

+0

哦,右@Peter。我誤解了代碼。謝謝。 – Gray 2012-08-07 14:03:54

+0

非常感謝,給構造函數添加一個參數對我來說就足夠了。我對BCEL做了一些研究。它可以在其字節碼中爲方法添加額外的參數。 – alicjasalamon 2012-08-07 14:19:39

-1

通過使用Thread.setName()

Read More here

+0

你是不是指'setName'? – 2012-08-07 15:11:11

+0

對不起,它是我的錯。它的setName – 2012-08-08 05:06:37