【问题标题】:Terminating a Runnable() object from main()从 main() 终止 Runnable() 对象
【发布时间】:2012-08-31 06:13:50
【问题描述】:

这是我的 Runnable 对象(在另一个类中):

private class StopFileCopy implements Runnable
{
     ObjectInputStream st;

     public Runnable(ObjectInputStream st)
     {
         this.st = st;
     }

     public void run()
     {
         if(st.read())
            stopWritingToFile = true;  // stopWritingToFile is an instance variable of the
                                       // class that contains this StopFileCopy class
     }
}

现在的问题是整数可能会或可能不会写入流“st”。如果没有,那么我需要立即从类外停止此 StopFileCopy 对象。我怎样才能做到这一点?

【问题讨论】:

  • 为什么不直接停止 Runnable 本身?
  • @biovamp ,st.read() 方法继续尝试从流“st”中读取一个整数。我不知道如何通知 StopFileCopy 类 run() 方法应该停止尝试从流中读取。

标签: java multithreading stream runnable


【解决方案1】:

如果我理解正确,那么您的问题是,st.read() 可能会永远阻塞。您可以做的是,您可以在经过一段时间后通过调用Thread.interrupt 来中断正在运行的线程。 (在您的可运行线程上从您的主线程执行此操作。)另一种方法是使用 FutureTask 传递您的可运行程序,然后在超时时调用它的 get()
顺便说一句,这是一个类似的问题:Is setting a timeout on ObjectInputStream.readObject() safe?


打断还有一件事很重要。它不会隐式停止阻塞,您必须继承 Thread 而不是实现 Runnable 并覆盖 interrupt 以关闭流(然后调用 super.interrupt)。另一种方法是关闭来自其他线程的流。

【讨论】:

  • 我对多线程没有很好的概念。你能告诉我如何中断一个线程吗?如果某个线程在某个时刻被中断,st.read() 方法是否也会停止工作?
  • @JisanMahmud:添加了更多细节。
猜你喜欢
  • 1970-01-01
  • 2011-08-22
  • 2020-09-22
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多