java - 如何停止/等待线程,然后稍后恢复/重新启动它

标签 java android multithreading service

我在后台运行一个服务,该服务也绑定(bind)到一个 Activity 以向 View 提供一些数据结果。 所以我的服务在后台运行,当我的 Activity 开始时我绑定(bind)服务并在它关闭时解除绑定(bind),而不管我的后台服务是否持续运行。 当我的 Activity 第一次启动时,这个服务首先被触发。

现在我已经在服务中创建了两个线程。一个用于后台工作。其他线程“displayThread”用于获取数据并将数据推送到 Activity 。

现在我的显示线程是这样的:

Thread displayThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                executeDisplayQueue();
            } catch (InterruptedException e){
                displayThread.interrupt();
            }
        }
});

因此,当我的 Activity 开始时,我的服务就会启动,并且我会启动两个线程:

@Override
public void onCreate() {
    super.onCreate();
    Log.d(LOG_TAG, "Creating Service......");
    thread.start();
    displayThread.start();
    Log.d(LOG_TAG, "Service is created.");
}

现在我想要的是,当我在 Activity 关闭时取消绑定(bind)我的服务时,我的“displayThread”停止或暂停,并在调用 rebind() 函数的 Activity 再次启动时重新启动或恢复。

@Override
public boolean onUnbind(Intent intent) {
    super.onUnbind(intent);
    // Stop/Pause/Wait my displayThread here
    return true;
}

@Override
public void onRebind(Intent intent) {
    super.onRebind(intent);
    // Restart/Resume my displayThread here
    Log.d(LOG_TAG, "trying to check display thread");
}

请在这里帮助我,因为我尝试了很多东西。 现在 displayThread.wait() 暂停了我的应用程序屏幕,所以它变黑了,好像一切都停止了,这当然不是正确的方法。

请给我一个关于如何进一步进行的解决方案。

编辑

这是 executeDisplayQueue() 函数:

@Override
    protected void executeDisplayQueue() throws InterruptedException {
        Log.d(LOG_TAG, "Starting execution of queue...");
        while (!Thread.currentThread().isInterrupted()) {
            SomeJob job = null;
            try {
                job = jobShowQueue.take();
                Log.d(LOG_TAG, "Taking Job no. " + job.getId() + " from the queue...");
                if (job.getJobState().equals(JobState.NEW)) {
                    Log.d(LOG_TAG, "Job state is NEW.");
                    job.setJobState(JobState.RUNNING);
                    job.getCmd().run(bluetoothSocket.getInputStream(), bluetoothSocket.getOutputStream());
                } else {
                    Log.e(LOG_TAG, "Job state is not NEW and therefore it should not be in Queue");
                }
            } catch (InterruptedException ie){
                Thread.currentThread().interrupt();
            } catch (UnsupportedCommandException u) {
                if (job != null)
                    job.setJobState(JobState.NOT_SUPPORTED);

            } catch (IOException ioe){
                job.setJobState(JobState.BROKEN_PIPE);

                Log.e(LOG_TAG, "Broken Pipe Error. Close the connection and restart again: "+ioe.getMessage());
            } catch (Exception e){
                job.setJobState(JobState.EXECUTION_ERROR);
                Log.e(LOG_TAG, "Failed to run Command. Error: "+e.getMessage());
            }
            if (job != null){
                Log.d(LOG_TAG, "Job is Finished.");
                final SomeJob finalJob = job;
                ((Activity) applicationContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((Activity) applicationContext).stateUpdate(finalJob);
                    }
                });
            }
        }
    }

所以基本上我是从队列中一个接一个地取出作业并将其填充到 Activity 中。因此,当我的 Activity 关闭时,我希望该线程 (displayThread) 停止,因为它不再需要填充任何内容。当它再次打开时,我的 displayThread 应该会自行重启。

最佳答案

您可以使用线程锁。 “executeDisplayQueue”方法中是否有while循环?您可能应该将 if(){lock.wait()} 放在 while 循环中。

private final Object displayThreadLock = new Object();
private boolean mIsBound;

Thread displayThread = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized(displayThreadLock) {
                if (!mIsBound) {
                    displayThreadLock.wait(); // this thread will wait here util displayThreadLock.notify() is called
                }
                try {
                    executeDisplayQueue();
                } catch (InterruptedException e){
                    displayThread.interrupt();
                }
            }
        }
});

@Override
public boolean onUnbind(Intent intent) {
    super.onUnbind(intent);
    // Stop/Pause/Wait my displayThread here
    mIsBound = false;
    return true;
}

@Override
public void onRebind(Intent intent) {
    super.onRebind(intent);
    // Restart/Resume my displayThread here
    mIsBound = true;
    synchronized(displayThreadLock) {
        displayThreadLock.notify(); // call notify to break the wait, so the displayThread continues to run
    }
    Log.d(LOG_TAG, "trying to check display thread");
}

关于java - 如何停止/等待线程,然后稍后恢复/重新启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32429588/

相关文章:

multithreading - 关于mongodb capped collections + tailable cursors的问题

android - 如何防止 Android 应用程序因后台线程中的 IOException 而崩溃?

java - 对具有任意属性的 HTML 文件的限制

Android 分享 Google Map V2 行程 (Facebook)

c++ - 创建共享 packaged_task 接受带转发的参数

android - Android JUnit 测试失败,没有像我预期的那样破坏我的 Ant 脚本?

android - 如何在Android中为按钮的文本加下划线?

java - 在哪里可以找到我本地创建的 X.509 证书的详细信息?

Java : naming convention for accessors

java - 方法的输入参数为异常时的Mock语句