java - 终止线程似乎不起作用
问题描述
我的服务类中有以下线程。
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。它不会终止。我不知道我做错了什么?
解决方案
此功能内置于 Thread。查看 thread.interrupt 和 thread.isInterrupted。没有理由重写此功能。
推荐阅读
- psake - 简单的 Psake 构建因“共享任务”异常而失败
- python - 如何将本地函数应用于python函数中数据框的特定列?
- sql - 使用 SQL 搜索字符串中出现次数最多的值
- python-3.x - 如何进行 72 小时倒计时
- java - 创建主题时如何从 Java Kafka AdminClient 获取详细的错误消息
- python - 使用python将逗号分隔值到Dict
- javascript - 将存储在数组中的文件附加到 HTML 文件输入 [jQuery]
- typescript - Typescript 将模板字符串编译为 es5,即使 tsconfig 目标设置为 ESNEXT
- c++ - 升级 Visual Studio 后 Bazel 不再工作
- google-apps-script - Google 脚本中的 Onchange 更改表数据