2012-03-21 151 views
4

我有一个包含可运行的线程。 我需要这个无限循环,除非用户取消。 我不知道如何去做这件事。所有的帮助非常感谢。 干杯。你如何循环线程?

+0

简单地运行一个循环很容易。但是您可能希望线程处理来自主线程的命令/工作项目,对吗?空闲时睡觉?当被告知时戒烟? – 2012-03-21 20:17:50

回答

9

我需要这个无限循环,除非用户取消。

很明显,你可以轻松地添加里面的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,以便在另一个线程中看到一个线程中字段的更改。

+0

完美的回应。这就是我需要的一切。干杯。 – 2012-03-21 20:34:06

+0

使用volatile布尔变量是安全的。所有对原始(和引用)类型的读写操作都是原子的(有时除了long和double)。 AtomicBoolean变量是一种矫枉过正,我想。 – Vladimir 2012-03-21 20:38:19

+0

不知道这是“矫枉过正”本身@弗拉基米尔,但'挥发性'也将工作,是的。 – Gray 2012-03-21 20:41:27