首页 > 解决方案 > 终止线程似乎不起作用

问题描述

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

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. 我已经建立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。它不会终止。我不知道我做错了什么?

标签: javaandroidmultithreadingterminate

解决方案


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


推荐阅读