Javaでロックされたスレッドを識別して処分する最良の方法
-
28-09-2019 - |
質問
新しいスレッド上の関数サードパーティモジュールを呼び出す必要があります。私が見たものから、すべてがうまくいった場合、コールはすぐに完了します。スレッドを起動して電話をかけて数秒間待つ良い方法は何ですか、スレッドがまだ生きている場合、それがロックされていると仮定して、非推奨の方法を使用せずにスレッドを殺す(または停止または放棄)します。
私は今のところこのようなものを持っていますが、これがそれを行うための最良の方法であるかどうかはわかりませんし、sward.stop()を呼び出してはならないので、それが非推奨です。ありがとう。
private void foo() throws Exception
{
Runnable runnable = new Runnable()
{
@Override
public void run()
{
// stuff that could potentially lock up the thread.
}
};
Thread thread;
thread = new Thread(runnable);
thread.start();
thread.join(3500);
if (thread.isAlive())
{
thread.stop();
throw new Exception();
}
}
解決
public void stop() {
if (thread != null) {
thread.interrupt();
}
}
このリンクを参照してください スレッドを停止する方法については、被写体をよくカバーします
他のヒント
(無条件)やりたいことをする方法はありません。たとえば、 stuff that could potentially lock up the thread.
このように見えますが、system.exit()に至るまで、それを止める方法はありません。
public void badStuff() {
while (true) {
try {
wait();
}
catch (InterruptedException irex) {
}
}
}
アプリが詰まったら、JStackを実行します(またはデバッガーを使用してください)。何が機能を貼り付けているのかを把握し、それを修正してみてください。
を調べます java.util.concurrent
Executor
フレームワーク、特に Future<T>
インターフェース。これらを使用すると、java.lang.threadの気まぐれから抽出され、タスクが実行されている方法からのデカップリングが得られます(別のスレッドで、スレッドがプールから来ているか、インスタンス化されているかにかかわらず、フライなど)
少なくとも将来のインスタンスはあなたに与えます isDone
と isCancelled
方法。
ExecutorService
(のサブインターフェイス Executor
)アウトスタンドタスクをシャットダウンする手段を提供します。または、をチェックしてください ExecutorService.awaitTermination(long timeout, TimeUnit unit)
方法
private void foo() throws Exception
{
ExecutorService es = Executors.newFixedThreadPool(1);
Runnable runnable = new Runnable()
{
@Override
public void run()
{
// stuff that could potentially lock up the thread.
}
};
Future result = es.submit(runnable);
es.awaitTermination(30, TimeUnit.SECONDS);
if (!result.isDone()){
es.shutdownNow();
}
}