启动/停止线程

Ant*_*lev 2 multithreading android

在锁定/解锁设备时,我找不到任何停止/恢复线程的工作解决方案,任何人都可以帮忙,或告诉我在哪里可以找到如何做到这一点?我需要在手机锁定时停止线程,并在手机解锁时再次启动它.

chu*_*ubs 10

Java在一个用于停止线程的协作中断模型上运行.这意味着你不能简单地在没有线程本身合作的情况下停止执行一个线程.如果要停止线程,客户端可以调用Thread.interrupt()方法来请求线程停止:

public class SomeBackgroundProcess implements Runnable {

    Thread backgroundThread;

    public void start() {
       if( backgroundThread == null ) {
          backgroundThread = new Thread( this );
          backgroundThread.start();
       }
    }

    public void stop() {
       if( backgroundThread != null ) {
          backgroundThread.interrupt();
       }
    }

    public void run() {
        try {
           Log.i("Thread starting.");
           while( !backgroundThread.interrupted() ) {
              doSomething();
           }
           Log.i("Thread stopping.");
        } catch( InterruptedException ex ) {
           // important you respond to the InterruptedException and stop processing 
           // when its thrown!  Notice this is outside the while loop.
           Log.i("Thread shutting down as it was requested to stop.");
        } finally {
           backgroundThread = null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

线程的重要部分是你不要吞下InterruptedException而是停止线程的循环和关闭,因为如果客户端请求线程中断本身,你只会得到这个异常.

因此,您只需将SomeBackgroundProcess.start()连接到事件以进行解锁,并将SomeBackgroundProcess.stop()连接到锁定事件.