【问题标题】:Terminate thread doesn't seem to be working终止线程似乎不起作用
【发布时间】:2019-11-22 08:34:24
【问题描述】:

我的服务类中有以下线程。

public class MyLocalThread extends Thread {
  @Override
  public void run() {
    while (!Thread.interrupted()) {
      try {
        //do some work
         Thread.sleep(4000);
      } catch (Exception e){
          System.out.println("Exception occur" + e.getMessage());
          e.printStackTrace();
      }
    }
  }
}

当我收到来自MainActivity.java 的 Intent 操作时,我正在尝试启动和停止线程。我已经建立了BroadcastReceiver 在服务和活动之间进行通信。我像下面这样开始线程。线程开始正常,我收到敬酒。

public class MyReceiver extends BroadcastReceiver {

    MyLocalThread thread = new MyLocalThread();

  @Override
  public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();

    if (action.equals("com.example.START")) {

      //starts the thread

      thread.start();

      Toast.makeText(context, "Service is started.", Toast.LENGTH_LONG).show();

    } else if (action.equals("com.example.STOP")) {

      //stops the thread
    thread.interrupt();
      Toast.makeText(context, "Service has stopped.", Toast.LENGTH_LONG).show();

    }
  }
}

但是当尝试停止我的线程时,即second action 不起作用。我收到一个服务已停止但我的线程仍在继续运行的 TOAST。它不会终止。我不知道我做错了什么?

【问题讨论】:

  • 在while循环中runnable在做什么?它会在等待输入时处于休眠状态或阻塞状态吗?
  • 我假设你有一个错字 - 运行方法应该是 while (!Thread.interrupted)。还要注意,当使用静态方法(与isInterrupted 实例方法相反)时,每次调用都会清除中断状态。 (isInterrupted上没有清除)。
  • 你还有一个竞争条件:start 不一定是立即的——它取决于调度程序——所以理论上你可能试图在线程启动之前停止它(中断)因此错过了一个中断(因为它没有开始)。

标签: java android multithreading terminate


【解决方案1】:

编辑:

您可以调用thread.interrupt() 来中断线程并将Thread.interrupted() 检查而不是创建布尔值。

class MyLocalThread extends Thread { 
    public void run() { 
      if(!Thread.interrupted()) {
        try {
        //do some work
       }
        catch (InterruptedException e) { 
            System.out.println("InterruptedException occur"); 
        } 
      }
    } 
}  

像这样中断线程:

MyLocalThread thread = new MyLocalThread(); 
        thread.start(); 
  // when need to stop the thread
        thread.interrupt(); 

【讨论】:

  • 这不会改变任何东西——如果 running 为 false,它将退出 while 循环,到达函数的底部,并自动返回。
  • Dex,感谢您的努力,我会验证并稍后回复您。
  • @cantona_7 我已经更新了答案。那应该行得通。但是要让您知道,我们无法阻止线程。我们只能通知系统中断它。
  • 我刚刚更新了问题,如果你看看你可以看到我的实现
  • Actullay 这个我已经看过了。我的方法是基于这篇文章。看来我错过了某个地方的情节。
【解决方案2】:

此功能内置于 Thread。查看 thread.interrupt 和 thread.isInterrupted。没有理由重写此功能。

【讨论】:

  • 嗨,但我不使用中断(),对吧?我想终止。对不起,如果这是一个愚蠢的问题。
  • Interrupt() 设置一个标志。 isInterrupted() 检查标志。这消除了对运行标志的任何需求,并且将正确实施。
  • 使用中断的好处是,如果线程正在等待,它将被一个 InterruptedException 唤醒,您可以采取措施很好地结束线程。
  • 你建议我做什么?使用中断()而不是终止?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多