你如何循环一个线程?

Ale*_*ock 5 multithreading android loops runnable

我有一个包含runnable的线程.除非用户取消,否则我需要无限循环.我不知道该怎么做.非常感谢所有帮助.干杯.

Gra*_*ray 11

除非用户取消,否则我需要无限循环.

显然,您可以在run()方法中轻松添加循环:

  new Thread(new Runnable() {
      public void run() {
          while (true) {
             // do something in the loop
          }
      }
  }).start();
Run Code Online (Sandbox Code Playgroud)

检查线程中断总是一个好主意:

  new Thread(new Runnable() {
      public void run() {
          // loop until the thread is interrupted
          while (!Thread.currentThread().isInterrupted()) {
             // do something in the loop
          }
      }
  }).start();
Run Code Online (Sandbox Code Playgroud)

如果您询问如何从另一个线程(例如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;
Run Code Online (Sandbox Code Playgroud)

我们需要使用a,volatile boolean以便在另一个线程中看到对一个线程中的字段的更改.