如何中断从方法内部创建的线程? [英] How can I interrupt a thread created from within a method?
问题描述
我知道您可以中断从一个可运行类创建的线程,但是如何中断从方法创建的该线程呢?使用易失的布尔值对我不起作用,因此我认为有更好的方法可以做到这一点,或者我需要以某种方式打断它.我不想中断所有线程,仅此一个.
I know that you can interrupt a thread created from say a runnable class, but how can I interrupt this thread I created from a method? Using a volatile boolean isn't working for me, so I assume either there is a better way to do this, or I need to somehow interrupt it. I don't want to interrupt all threads, just this one.
我创建了一个启动像这样的线程的方法:
I created a method that kicks off a Thread like this:
public static void StartSyncThread() {
new Thread() {
public void run() {
isRunning = true; // Set to true so while loop will start
while (isRunning) {
...
}
} // Close run()
}.start();
}
....
public static void KillSyncThread() {
isRunning = false;
}
推荐答案
如果您保留对该线程的引用:
If you keep a reference to the thread:
private static Thread myThread;
public static void StartSyncThread() {
myThread = new Thread() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
...
}
} // Close run()
}
myThread.start();
}
然后您可以致电
public static void killSyncThread() {
if (myThread != null && myThread.isAlive()) {
myThread.interrupt();
}
}
取消.这样,您就可以摆脱静态的isRunning标志,interrupt()设置与之等效的内置标志,另外它将唤醒线程从睡眠或等待状态.
to cancel it. This way you can get rid of the static isRunning flag, interrupt() sets a built-in flag that's equivalent to that, plus it will wake the thread up from sleeping or waiting.
如果您确实确实将变量声明为volatile,则其更新值应该在线程之间可见.如果您正在测试的标志与您设置的标志不同,这可能是一个范围界定问题吗?在全局可变状态下,它似乎很快就会变得令人费解.举一个小例子,并亲自验证设置标志或中断线程是否有效,然后充满信心地寻找真正的问题.
If you really did declare the variable as volatile then its updated value should be visible across threads. Could be this is a scoping problem where the flag you're testing isn't the same as what you're setting? With global mutable state it seems likely it could get convoluted fast. Make a small example and verify for yourself that setting the flag or interrupting the thread works, then with that confidence you can look for the real problem.
这篇关于如何中断从方法内部创建的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!