gpt4 book ai didi

java - Thread 或 Runnable 如何立即被杀死

转载 作者:行者123 更新时间:2023-12-01 12:53:11 25 4
gpt4 key购买 nike

我有一个小问题。我有一个服务,当 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();
}
}

现在线程在循环中有一个 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 并在超时出现之前终止它,但这只是一个案例

最佳答案

尝试阅读this article

Implementing cancelable tasks

Nothing in the language specification gives interruption any specific semantics, but in larger programs, it is difficult to maintain any semantics for interruption other than cancellation. Depending on the activity, a user could request cancellation through a GUI or through a network mechanism such as JMX or Web Services. It could also be requested by program logic. For example, a Web crawler might automatically shut itself down if it detects that the disk is full, or a parallel algorithm might start multiple threads to search different regions of the solution space and cancel them once one of them finds a solution.

Just because a task is cancelable does not mean it needs to respond to an interrupt request immediately. For tasks that execute code in a loop, it is common to check for interruption only once per loop iteration. Depending on how long the loop takes to execute, it could take some time before the task code notices the thread has been interrupted (either by polling the interrupted status with Thread.isInterrupted() or by calling a blocking method). If the task needs to be more responsive, it can poll the interrupted status more frequently. Blocking methods usually poll the interrupted status immediately on entry, throwing InterruptedException if it is set to improve responsiveness.

The one time it is acceptable to swallow an interrupt is when you know the thread is about to exit. This scenario only occurs when the class calling the interruptible method is part of a Thread, not a Runnable or general-purpose library code, as illustrated in Listing 5. It creates a thread that enumerates prime numbers until it is interrupted and allows the thread to exit upon interruption. The prime-seeking loop checks for interruption in two places: once by polling the isInterrupted() method in the header of the while loop and once when it calls the blocking BlockingQueue.put() method.

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(); }}

关于java - Thread 或 Runnable 如何立即被杀死,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com