2017-02-08 6 views
0

私はメソッドが呼び出されるJavaのスレッドを持っています。私はそれを殺すことができるように各スレッドのマップを保存しています。 私のサンプルコードは次のとおりです。私は私のストップ法、T呼び出されたときに問題があるJavaでのスレッド実行時間

public static void stop(String threadName) { 

    if (StringUtils.isNotEmpty(threadName)) { 
     Thread t = threadMap.get(threadName); 

     if (t != null && t.isAlive()) { 
      System.out.println("Going to kill the thread:" + threadName); 
      t.interrupt(); 
      System.out.println("killed!!"); 
     } else { 
      System.out.println("THREAD is null"); 
     } 
    } 

} 

:私はのようなものを持っているので、

Thread thread = new Thread(new Runnable() { 

     public void run() { 

      executeMethod(); 

     } 
    }); 

    thread.start(); 
    thread.setName("some Name"); 
    //Create Map to save each method call as thread 
    threadMap.put("some Name", thread); 

は、今私はスレッドを殺すことで、メソッドの呼び出しを停止したいです。 isAlive()はfalseです。私は、メソッドの実行時間はスレッドの生きている時間になると仮定します.Am私は正しいか、それを誤解していますか?

答えて

-1

スレッドのメソッドと実行時間の実行時間は異なります。 Hereのどのスレッドのライフサイクル言う:

スレッドはstart()メソッドの呼び出し後に実行可能な状態になっているが、スレッドスケジューラが実行中のスレッドにすることを選択していません。

したがって、start()メソッドの呼び出しは必ずしもスレッドの実行を保証するものではありません。これは、jvmとOpetating Systemがスレッドをどのように処理するかによって異なります。スレッドはexecuteMethodメソッドを開始する前にrunnable状態にしておくか、またはstart()が呼び出されるとすぐにexecuteMethodを開始することがありますが、これらのいずれかの動作は保証されません。これは、javadocの言うことです:

すべてのスレッドが優先されます。優先度の高いスレッドは優先度の低いスレッドに優先して実行されます。各スレッドは、デーモンとしてマークされていてもいなくてもよい。あるスレッドで実行されているコードが新しいThreadオブジェクトを作成すると、新しいスレッドの優先順位は作成スレッドの優先順位と同じに設定され、デーモンスレッドの場合はデーモンスレッドになります。

したがって、スレッドの有効時間をメソッドの実行時間と見なすべきではありません。

+0

両方の引用では、isAlive()メソッドによって返される値は記録されません。このようなロジックでは、isAlive()メソッドを呼び出しているので、呼び出しコードが実行されているため、スレッドが実行されていないため、単一のコアCPUシステムでtrueを返すべきではありません。 – h22

+0

私はOPの次の質問に答えました。「メソッドの実行時間はスレッドの生存時間と仮定します。 'isAlive()'メソッドでどの値を返すべきかという疑問はないと思ってください。 –

0

スレッドはまたrun()メソッドの後にも死ぬ。そのような場合、スレッドは生きていません。 sleepステートメントをrun()メソッドに追加し、ステートメントの前後にprintステートメントを追加してスレッドの現在の状態を確認します。

Thread.interruptはスレッドを強制終了しますが、一時停止した場合は再開しますが、通常は手動でスレッドを強制終了することはお勧めしません。理由とその対処方法を理解するためにthis questionを読んでください。

0
As per Thread Class java doc 
    https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html 

Thread.getState() will return you state of the thread 
which you can check if thread is still running and then can kill it. 

Thread.State = getState() Returns the state of this thread. 

A thread state. A thread can be in one of the following states: 
NEW 
A thread that has not yet started is in this state. 
RUNNABLE 
A thread executing in the Java virtual machine is in this state. 
BLOCKED 
A thread that is blocked waiting for a monitor lock is in this state. 
WAITING 
A thread that is waiting indefinitely for another thread to perform a particular action is in this state. 
TIMED_WAITING 
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. 
TERMINATED 
A thread that has exited is in this state. 
関連する問題