如何创建一个无限的Thread实例循环?

时间:2015-08-21 01:52:41

标签: java multithreading loops java-threads

我想创建线程来操纵它们(运行,等待,停止)。我知道如何逐个制作一个实例

实现runnable的类

public class ThreadRunner implements Runnable{ .....

我创建对象的类

ThreadRunner thread1 = new ThreadRunner ("thread1");
ThreadRunner thread2 = new ThreadRunner ("thread2"); 
.
.
.
thread1.start()
.
.

我想要一个只在用户想要时结束的循环(可能带有布尔标志)。如何每隔10秒创建一个动态实例的循环?

1 个答案:

答案 0 :(得分:0)

boolean stop = false;
List<Thread> threads = new ArrayList<Thread>();
while (!stop) {
    Thread t = new ThreadRunner("Thread " + threads.size());
    t.start();
    threads.add(t);
    // Do something here to check whether 'stop' should be updated.
    // And wait for 10 seconds here
}