android - 为什么线程不停止?

标签 android multithreading

我的服务生成一个新线程,并根据 typically recommended java 停止它中断()的方法。当我停止服务时,我停止了 onDestroy() 中的线程。服务停止,到达中断代码。但是,线程很快就会从 Runnable 的开头重新启动。

public class DoScan extends Service {
    public volatile Thread runner;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        startThread();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.onDestroy");
        stopThread();
    }


    public synchronized void startThread(){
        if(runner == null){
            android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.startthread");     
            runner = new Thread(new ScanningThread());
            runner.start();
        }
    }
    /* use a handler in a loop cycling through most of oncreate.
     * the scanningthread does the work, then notifies the svc's uithread
     */

    public synchronized void stopThread(){
        if(runner != null){
            android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.stopthread");
            Thread moribund = runner;
            runner = null;
            moribund.interrupt();
            android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "interrupted?" + moribund.isInterrupted());
        }
    }
        }

最佳答案

我认为最安全的方法是设置一个标志,以便线程在其主循环中检查它。

class ScanningThread extends Thread {
    // Must be volatile:
    private volatile boolean stop = false;

    public void run() {
        while (!stop) {
            System.out.println("alive");
        }
        if (stop)
            System.out.println("Detected stop");
    }

    public synchronized void requestStop() {
        stop = true;
    }
}

public synchronized void startThread(){
    if(runner == null){
        android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.startthread");         
        runner = new ScanningThread();
        runner.start();
    }
}

public synchronized void stopThread(){
    if(runner != null){
        android.util.Log.v("@@@@@@@@@@@@@@@@@@@@", "DoScan.stopthread");
        runner.requestStop();
        runner = null;
    }
}

关于android - 为什么线程不停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1204012/

相关文章:

java - 使用信号量

android - 自定义标题栏问题

android - Google Maps API key 是否缓存在 Android 上?

具有全息灯主题的 Android 对话框 Activity

c++ - 基本线程导致 malloc() : memory corruption:

Python:传递函数更多信息是一件坏事吗?

android - 用于设置 ImageView 的 AsyncTask

javascript - 在 Android Webview 中加载远程 html 页面后添加 javascript 代码

c# - 在我的 C# 应用程序中,Thread.Start 在一些稀疏的情况下没有返回

multithreading - 我应该在 Clojure 中使用哪一个?去 block 或线程?