终止线程似乎不起作用

时间:2019-07-12 14:41:52

标签: java android multithreading terminate

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

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消息。它不会终止。我不知道我在做什么错?

2 个答案:

答案 0 :(得分: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(); 

答案 1 :(得分:1)

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