繁体   English   中英

启动/停止线程

[英]Start/stop thread

在锁定/解锁设备时,我找不到任何有效的解决方案来停止/恢复线程,任何人都可以帮忙,或者告诉我在哪里可以找到它怎么做? 我需要在手机锁定时停止线程,并在手机解锁时再次启动它。

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;
        }
    }

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

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

暂无
暂无

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

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