我通过实现可运行接口创建了类,然后在我项目的其他一些类中创建了许多线程(近 10 个)。
如何停止其中一些线程?
6 回答
最简单的方法是interrupt()它,这将导致Thread.currentThread().isInterrupted()return ,并且在线程正在等待的某些情况下true也可能抛出一个,例如,等。InterruptedExceptionThread.sleep()otherThread.join()object.wait()
在run()方法内部,您需要捕获该异常和/或定期检查该Thread.currentThread().isInterrupted()值并执行某些操作(例如,突破)。
注意:虽然Thread.interrupted()看起来与 相同,但它有一个讨厌的isInterrupted()副作用:调用会interrupted() 清除interrupted标志,而调用isInterrupted()不会。
其他非中断方法涉及使用volatile正在运行的线程监视的“停止”() 标志。
如何停止通过实现可运行接口创建的线程?
有很多方法可以停止线程,但它们都需要特定的代码来执行此操作。停止线程的典型方法是拥有一个volatile boolean shutdown线程经常检查的字段:
// set this to true to stop the thread
volatile boolean shutdown = false;
...
public void run() {
while (!shutdown) {
// continue processing
}
}
您还可以中断导致sleep(),wait()和其他一些方法抛出的线程InterruptedException。您还应该使用以下内容测试线程中断标志:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// continue processing
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// good practice
Thread.currentThread().interrupt();
return;
}
}
}
请注意,中断线程不一定interrupt()会立即引发异常。只有当你在一个可中断的方法中时才会被抛出。InterruptedException
如果你想为shutdown()你的类添加一个实现的方法Runnable,你应该定义你自己的类,如:
public class MyRunnable implements Runnable {
private volatile boolean shutdown;
public void run() {
while (!shutdown) {
...
}
}
public void shutdown() {
shutdown = true;
}
}
在使用中途停止线程Thread.stop()不是一个好习惯。更合适的方式是让线程以编程方式返回。让 Runnable 对象在方法中使用共享变量run()。每当您希望线程停止时,将该变量用作标志。
编辑:示例代码
class MyThread implements Runnable{
private Boolean stop = false;
public void run(){
while(!stop){
//some business logic
}
}
public Boolean getStop() {
return stop;
}
public void setStop(Boolean stop) {
this.stop = stop;
}
}
public class TestStop {
public static void main(String[] args){
MyThread myThread = new MyThread();
Thread th = new Thread(myThread);
th.start();
//Some logic goes there to decide whether to
//stop the thread or not.
//This will compell the thread to stop
myThread.setStop(true);
}
}
不建议中途停止(杀死)线程。API 实际上已被弃用。
但是,您可以在此处获取更多详细信息,包括解决方法:How do you kill a Thread in Java?
Thread.currentThread().isInterrupted() 运行良好。但这段代码只是暂停计时器。
此代码是停止并重置线程计时器。 h1 是处理程序名称。 此代码添加在您的按钮单击侦听器中。w_h =分钟 w_m =毫秒 i=计数器
i=0;
w_h = 0;
w_m = 0;
textView.setText(String.format("%02d", w_h) + ":" + String.format("%02d", w_m));
hl.removeCallbacksAndMessages(null);
Thread.currentThread().isInterrupted();
}
});
}`