2010-06-17 97 views
1

我必须在新线程上调用第三方功能模块。从我所看到的情况来看,如果一切进展顺利,或者只是挂起线索锁定,呼叫就会很快完成。有什么方法可以启动线程并进行调用并等待几秒钟,如果线程仍然活着,然后假设它已被锁定,则可以在不使用任何废弃方法的情况下杀死(或停止或放弃)线程。在java中识别和处理锁定线程的最佳方法

我现在有类似的东西,但我不确定这是否是最好的方式来做到这一点,我想避免调用Thread.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(); 
     } 

} 
+0

所以基本上你想启动一个线程,然后停止它,如果它仍然活着一段时间后? – 2010-06-17 19:15:39

+0

@matt_b是的,正好! – 2010-06-17 19:43:02

回答

2
public void stop() { 
     if (thread != null) { 
      thread.interrupt(); 
     } 
    } 

See this link上如何停止一个线程,它涵盖的主题以及

+1

我投票,因为调用你的方法'停止'显示对线程中断充其量天真和不正确的理解。作为FYI @Romain Hippeau,仅仅因为你在线程中调用中断并不意味着它会停止。如果这段代码的执行足够糟糕而导致死锁,那肯定是不足以错误地处理InterruptedException,或者不适当地检查中断标志。 – 2010-06-17 22:54:33

+0

@Tim Bender - 问题是如何阻止线程。例程的实施不是问题的一部分。如果你阅读我在答案中的链接,它涵盖了所有这些。为了记录,让它显示“我认为投票不公平”。附:感谢您为解释为什么而不是只是downvoting(我讨厌这个) – 2010-06-18 01:38:13

0

我将调查java.util.concurrentExecutor框架,特别是Future<T>接口。有了这些,你可以从java.lang.Thread的变化中抽象出一些东西,并且你可以很好地分离它们的运行方式(无论是在单独的线程上,线程是来自池还是实例化飞等)

未来的实例,至少,给你isDoneisCancelled方法。

ExecutorServiceExecutor的子接口)为您提供了一些关闭任何排出任务的方法。或检查出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(); 
     } 

} 
1

有没有办法做你想要什么(无条件)。例如,如果stuff that could potentially lock up the thread.看起来是这样,没有办法阻止它,永远短System.exit()的组成:

public void badStuff() { 
while (true) { 
    try { 
    wait(); 
    } 
    catch (InterruptedException irex) { 
    } 
} 
} 

当你的应用程序卡住,运行jstack(或使用调试器)。尝试找出什么坚持了功能,并修复它。

+1

或使用以下命令获取JVM转储:kill -QUIT pid – 2010-06-17 19:29:58

+1

只适用于unix,jstack是跨平台的。 – Justin 2010-06-17 19:30:56

+0

不幸的是,我调用的函数在第三方模块中,我无法控制它。所以,除非我从模块的作者那里得到更新,否则无法解决它。 – 2010-06-17 19:46:56

相关问题