如何立即杀死Thread或Runnable

时间:2014-06-05 13:26:18

标签: java android multithreading

我有点问题。我在启动onStartCommand()时获得SingleTon线程的服务。

public int onStartCommand(Intent intent, int flags, int startId) 
{
   Thread t = myThreadFactory.getConnectionThreadWhatever();
   if (t.isAlive() && !t.isinterrupted()) 
   { 
     // do actions when thread is already alive
   } 
   else 
   { 
     // do actions to start and run the thread. e.g. t = new ConnectionThread().start();
   }
}

现在,Thread在循环中有一个Runnable,就像(伪代码!)

public static boolean isRunning = false;
public void run() 
{
   isRunning = true;
   while (isRunning) 
   {
       // open the httpconnection with a (read)timeout of 300 (long polling, whatever) 
   }
}

现在i =我想在网络广播接收器或任何情况下连接断开后立即终止线程。

在超时(例如300秒)发生之前不等待而立即杀死它的常见方法是什么?

目前我在

的另一个班级中这样做
public void stopThreadconnectionInstantlyWhatever() 
{
   ConnectionThread.isRunning = false;
   Thread t = myFactory.getConnectionThread();
   t.interrupt();
}

现在的问题似乎是线程可能要等到发生时间,但每秒钟都应该避免更多的电池使用。所以..任何想法? : - )

好吧,我可以使用单例模式获取httpurlconnection并在超时出现之前终止它,但这只是一个案例

1 个答案:

答案 0 :(得分:1)

尝试阅读this article

  

实施可取消的任务

语言规范中没有任何内容可以中断任何特定的语义,但是更大   程序,很难维护任何语义中断   除了取消。根据活动,用户可以   请求通过GUI或通过网络机制取消   作为JMX或Web服务。它也可以由程序逻辑请求。   例如,Web爬网程序可能会自动关闭它   检测到磁盘已满,或者可能启动并行算法   多个线程来搜索解空间的不同区域和   一旦其中一个找到解决方案,取消它们。

仅仅因为任务是   可取消并不意味着它需要响应中断请求   立即。对于在循环中执行代码的任务,它是常见的   每次循环迭代只检查一次中断。取决于如何   循环需要执行,它可能需要一些时间才能执行   任务代码通知线程已被中断(通过轮询   Thread.isInterrupted()或通过调用a中断状态   阻塞方法)。如果任务需要更具响应性,则可以进行轮询   中断状态更频繁。阻止方法通常是轮询   投掷后立即中断状态   InterruptedException如果设置为提高响应速度。

一个   当你知道的时候,吞下一个中断是可以接受的   线程即将退出。此方案仅在类时发生   调用可中断方法是Thread的一部分,而不是Runnable   或通用库代码,如清单5所示   创建一个枚举素数的线程,直到它被中断   并允许线程在中断时退出。寻求主要的   循环检查两个地方的中断:一次通过轮询   while循环的标题中的isInterrupted()方法和一次   它调用阻塞的BlockingQueue.put()方法。

public class PrimeProducer extends Thread {
private final BlockingQueue<BigInteger> queue;

PrimeProducer(BlockingQueue<BigInteger> queue) {
    this.queue = queue;
}

public void run() {
    try {
        BigInteger p = BigInteger.ONE;
        while (!Thread.currentThread().isInterrupted())
            queue.put(p = p.nextProbablePrime());
    } catch (InterruptedException consumed) {
        /* Allow thread to exit */
    }
}

public void cancel() { interrupt(); }}