简体   繁体   English

Android终止通过runnable创建的线程

[英]Android terminating a thread created through runnable

Let's say in various points in my application, I create and fire off a new runnable like so: 假设在我的应用程序的各个方面,我创建并触发了一个新的可运行对象,如下所示:

new Thread(new Runnable() { 
    public void run() {
    while(true) {
       //do lots of stuff
       //draw lots of stuff on screen, have a good ol time
       //total loop processing time abt 1250-1500ms
       //check for conditions to stop the loop, break;
   }    }   }

Now, is there any way to terminate that thread midway through execution other than break; 现在,除了break;以外,还有没有其他方法可以在执行过程中终止该线程break; inside my while loop? 在我的while循环中? I'd like to be able to kill it specifically and immediately from the parent thread, like, as in the event that the user just requested to load a different map. 我希望能够立即从父线程中将其杀死,例如,在用户刚刚请求加载其他地图的情况下。 It feels clunky to insert an if (stopFlag) break; 插入if (stopFlag) break;感觉很if (stopFlag) break; (set in parent thread) after every 5 or so lines of code. (大约在每5行代码之后)(在父线程中设置)。

I peeked at Runnable's and Thread's methods and I just can't see it. 我偷看了Runnable和Thread的方法,但看不到它。 Someone know an awesome trick? 有人知道很棒的把戏吗?

您可以使用AsyncTask并调用cancel取消线程。

Instead of while (true) you may check for a condition or a flag that would be changed properly when the Thread/Runnable should be stopped. 除了while (true)您还可以检查在应停止线程/可运行对象时是否可以正确更改的条件或标志。 This seems to be the suggested strategy since Thread.stop() has been deprecated. 由于不建议使用 Thread.stop(),因此这似乎是建议的策略

You could use AsyncTask as suggested, which probably works best in this case. 您可以按照建议使用AsyncTask,在这种情况下,它可能效果最好。 I believe you can also use the interrupt() method, which is preferred if good if you're not in Android, but still suffers from having to explicitly check if it is interrupted: 我相信您也可以使用interrupt()方法,如果您不在Android中,则该方法在较好的情况下将是首选方法,但是仍然必须明确检查它是否被中断:

Thread t = new Thread(new Runnable() {
    public void run() {
        while (true) {
            // do some stuff
            if (isInterrupted()) {
                break;
            }
        }
     });
t.start();

// Whoa! Need to stop that work!
t.interrupt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM