【问题标题】:How do you loop a thread?你如何循环一个线程?
【发布时间】:2012-03-21 20:12:21
【问题描述】:

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

【问题讨论】:

  • 简单地运行一个循环很容易。但是您可能希望线程处理来自主线程的命令/工作项,对吧?空闲时睡觉?并在被告知时退出?

标签: android multithreading loops runnable


【解决方案1】:

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

显然,您可以轻松地在 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 boolean,以便在一个线程中对字段的更改可以在另一个线程中看到。

【讨论】:

  • 完美响应。这就是我需要的一切。干杯。
  • 使用 volatile 布尔变量是安全的。对任何原始(和引用)类型的所有读取和写入始终是原子的(有时 long 和 double 除外)。我认为 AtomicBoolean 变量有点过头了。
  • 不确定@Vladimir 本身是否“矫枉过正”,但volatile 也可以,是的。
猜你喜欢
  • 2021-01-18
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多