代码之家  ›  专栏  ›  技术社区  ›  Bala R

java中识别和处理锁定线程的最佳方法

  •  1
  • Bala R  · 技术社区  · 16 年前

    我现在有类似的东西,但我不确定这是否是最好的方法,我想避免调用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();
            }
    
    }
    
    3 回复  |  直到 16 年前
        1
  •  2
  •   Romain Hippeau    16 年前
    public void stop() {
            if (thread != null) {
               thread.interrupt();
            }
        }
    

    See this link

        2
  •  1
  •   Justin    16 年前

    没有办法(无条件地)做你想做的事。例如,如果 stuff that could potentially lock up the thread. 看起来像这样,没有办法阻止它,永远缺少系统。exit():

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

        3
  •  0
  •   Scott Bale    16 年前

    java.util.concurrent Executor Future<T>

    一个未来的例子,至少,给你 isDone isCancelled 方法。

    ExecutorService (子接口) 遗嘱执行人 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();
            }
    
    }
    
    推荐文章