2016-04-02 18 views
1

私は余分なメソッドでカスタムスレッドを作成しました。私はループ内にいくつかのスレッドを作成しました。カスタムスレッドメソッドへのアクセス

以下に示すように、Thread.getAllStackTraces()を使用して余分なメソッドを実行できるかどうかを知りたいと考えました。

public class CustomThread extends Thread 
{ 

    int pid; 

    CustomThread(int processID) 
    { 
     this.pid = processID; 
    } 

    @Override 
    public void run() 
    { 
     System.out.println("Thread running"); 
    } 

    public void printDetails() 
    { 
     System.out.println("PID "+this.pid); 
    } 
} 


public class Main 
{ 

    public static void main(String[] args) 
    { 
     for(int i = 0;i<5;i++){ 
      CustomThread ct = new CustomThread(1); 
      ct.start(); 
     } 
    } 
    System.out.println(Thread.getAllStackTraces().get(0).printDetails); <- Is it possible to access the method like this? 

} 
+0

'printDetails'メソッドはCustomThreadに属しますが、' Thread.getAllStackTraces()。get(0) 'は' StackTraceElement [] '(配列)を返します。 – Hackerdarshi

答えて

2

私はエフゲニーは、タイピングのスピードで私を殴られたことがわかり、これを入力しながら、しかし、私が指摘したいのですが、あなたの場合は
あなたが最初のスレッドを取得するThread.getAllStackTraces().keySet().get(0)を必要とするか、マップ全体のキーを反復処理することができますいくつかのこと。彼の方法は正しいですが、あなたに任意の出力を与えることはありません。

ここでの最初のメソッドで精緻である:

Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces(); 
Set<Thread> threads = map.keySet();//Get the keys of the map, in this case the key is the thread 
for(Thread thread : threads){//iterate over all the threads 
    if(thread instanceof CustomThread){//check to see if it is one of our custom threads 
     CustomThread custom = (CustomThread)thread;//cast it to a custom thread 
     custom.printDetails();//call your method 
    } 
} 

そして、あなたのスレッドがあるため、この方法は(まだ)あなたのフィードバックを与えることはありませんこれが実行される時点で既に死んでいる。

@Override 
public void run() { 
    System.out.println("Thread running"); 
    while(true){}//add this to keep the thread alive 
} 

これをテストするには、無限ループwhileループをスレッドに追加するだけで、メソッドが機能します。

また、1を使用しているループでPIDとしてiを使用する代わりに、すべてのスレッドで同じPIDが使用されます。私はこのことができます:)

P.S.を願っています

for(int i = 0;i<5;i++){ 
    CustomThread ct = new CustomThread(i); 
    ct.start(); 
} 

:だから、すべてのカスタムは、あなたが使用できる別のPIDスレッド与えますエフゲニーは最初に信用供与期限が到来していたので信用できた。

3

Thread.getAllStackTraces()すべてのライブスレッドのスタックトレースマップを返します。マップキーはスレッドであり、各マップ値は、対応するスレッドのスタックダンプを表すStackTraceElementの配列です。

Map<Thread, StackTraceElement[]>が返されます。get(0)の要素を取得できません。 Threadインスタンスをキーとして提供する必要がありますが、StackTraceElement[]が得られます。

for (Thread t : Thread.getAllStackTraces().keySet()) { 
    if (t instanceof CustomThread) { 
     ((CustomThread)t).printDetails();; 
    } 
} 
+0

Hi。私はこの答えを使用しましたが、5つのスレッドが作成されていますが、ループは1回反復します。 "instanceof"条件文を削除すると、5つのスレッドすべてが反復処理されます。 –

+1

@ Vimlan.Gループは、 'getAllStackTraces()'が呼び出される前に他のスレッドが作業を終了するため、一度反復します。ローンは彼の答えでそれを言いました。 'CustomThread'実行メソッドに何かを追加して、スレッドをより長く動作させる必要があります。 'Thread.sleep()'または無限ループです。 "instanceof"を削除すると、ClassCastExceptionが発生する可能性があります。 – Evgeny

関連する問題