Java 如何立即终止线程或可运行线程

Java 如何立即终止线程或可运行线程,java,android,multithreading,Java,Android,Multithreading,我有个小问题。我有一个服务,当onStartCommand()被触发时,它会得到一个单线程 public int onStartCommand(Intent intent, int flags, int startId) { Thread t = myThreadFactory.getConnectionThreadWhatever(); if (t.isAlive() && !t.isinterrupted()) { // do actions

我有个小问题。我有一个服务,当onStartCommand()被触发时,它会得到一个单线程

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();
   }
}
现在线程在循环中有一个Runnable,类似于(伪代码!)

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

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

目前,我在另一个班级与

public void stopThreadconnectionInstantlyWhatever() 
{
   ConnectionThread.isRunning = false;
   Thread t = myFactory.getConnectionThread();
   t.interrupt();
}
现在的问题似乎是线程可能会等到超时发生,但每秒钟都会有更多的电池使用,这应该避免。所以有什么想法吗?:-)

嗯,我也可以使用单例模式获取httpurlconnection,并在超时出现之前将其杀死,但这只是一个例子

实现可取消的任务

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

仅仅因为任务 可取消并不意味着它需要响应中断请求 马上。对于在循环中执行代码的任务,通常 每次循环迭代仅检查一次中断。取决于如何 循环执行所需的时间很长,可能需要一段时间才能执行 任务代码注意到线程已被中断(通过轮询或 使用Thread.isInterrupted()或通过调用 阻塞方法)。如果任务需要更具响应性,它可以轮询 中断状态更频繁。阻塞方法通常是轮询 进入时立即中断状态,抛出 InterruptedException(如果设置为提高响应性)

那个 接受中断的时间是当你知道 线程即将退出。只有当类 调用可中断方法是线程的一部分,而不是可运行的 或通用库代码,如清单5所示。信息技术 创建枚举素数直到中断的线程 并允许线程在中断时退出。首要任务 循环在两个位置检查中断:一次通过轮询 isInterrupted()方法,该方法位于while循环的头中,并在 它调用blocking BlockingQueue.put()方法

公共类PrimeProducer扩展线程{
私有最终阻塞队列;
PrimeProducer(阻塞队列){
this.queue=队列;
}
公开募捐{
试一试{
BigInteger p=BigInteger.1;
而(!Thread.currentThread().isInterrupted())
put(p=p.nextProbablePrime());
}捕获(中断异常消耗){
/*允许线程退出*/
}
}
public void cancel(){interrupt();}}

@emanuelsibold Thread.sleep()抛出InterruptedException,并在被中断时停止。httpconnection的文档中没有处理线程中断的地方吗?@EmanuelSeibold通常有一种优雅的方式。如果有东西等待或阻塞很长时间,几乎总是有某种方法可以唤醒它,而不只是终止线程。你在个案的基础上处理这些事情。这就是他们反对Thread.stop()的原因,因为总有更好的方法。我们需要更多关于等待的细节,因为这将改变如何唤醒它。我认为这里的关键是任何阻塞的东西都应该抛出InterruptedException。OP需要显示阻塞的代码
public void stopThreadconnectionInstantlyWhatever() 
{
   ConnectionThread.isRunning = false;
   Thread t = myFactory.getConnectionThread();
   t.interrupt();
}
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(); }}