I need this to loop infinitely unless cancelled by the user.
显然你可以在run()方法中轻松添加一个循环:
new Thread(new Runnable() {
public void run() {
while (true) {
// do something in the loop
}
}
}).start();
检查线程中断总是一个好主意:
new Thread(new Runnable() {
public void run() {
// loop until the thread is interrupted
while (!Thread.currentThread().isInterrupted()) {
// do something in the loop
}
}
}).start();
如果您询问如何从另一个线程(例如UI线程)取消线程操作,那么您可以执行以下操作:
private final volatile running = true;
...
new Thread(new Runnable() {
public void run() {
while (running) {
// do something in the loop
}
}
}).start();
...
// later, in another thread, you can shut it down by setting running to false
running = false;
我们需要使用volatile布尔值,以便在另一个线程中看到对一个线程中的字段的更改.