终止线程似乎不起作用
Terminate thread doesn't seem to be working
我的服务中有以下线程 class。
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
以在服务和 activity 之间进行通信。我像下面这样启动线程。线程开始正常,我收到祝酒词。
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.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();
Thread 中内置了此功能。查看 thread.interrupt 和 thread.isInterrupted。没有理由重写此功能。
我的服务中有以下线程 class。
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
以在服务和 activity 之间进行通信。我像下面这样启动线程。线程开始正常,我收到祝酒词。
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.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();
Thread 中内置了此功能。查看 thread.interrupt 和 thread.isInterrupted。没有理由重写此功能。