【发布时间】: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