我有下面的类,我通常运行大约 10 个线程
public class MyClass implements Runnable {
private volatile Device device = null;
public MyClass(Device device) {
this.device = device;
}
@Override
public void run() {
while (true) { // <--- I do know that the "true" has to be changed to a Boolean
try {
Worker worker = new Worker();
worker.work();
System.out.println("Waiting 6 seconds!");
Thread.sleep(6 * 1000);
System.out.println("------------------------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Thread in program ended!");
}
}
在我的 main 中,我是这样开始线程的
for (int i = 0; i < 2; i++) {
(new Thread(new MyClass())).start();
}
这是一个基于控制台的程序。结束程序最可靠的方法是什么?我认为最好的方法是将 while (true)
更改为 while (Boolean)
并以某种方式更改所有线程的 boolean 值,然后当循环结束时,程序将优雅地结束。
最佳答案
这里我通过等待用户输入来结束它,但您可以将其更改为从任何地方触发停止方法
public static void main(String[] args) {
List<MyClass> myThreads = new ArrayList<>();
for (int i = 0; i < 2; i++) {
MyClass myClass = new MyClass();
Thread t = new Thread(myClass);
t.start();
myThreads.add(myClass);
}
Scanner in = new Scanner(System.in);
in.next();
for(MyClass t : myThreads){
t.stop();
}
}
class MyClass implements Runnable {
private Boolean flag;
public MyClass() {
this.flag = true;
}
@Override
public void run() {
while (flag) { // <--- I do know that the "true" has to be changed to a Boolean
try {
System.out.println("Waiting 6 seconds!");
Thread.sleep(6 * 1000);
System.out.println("------------------------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("Thread in program ended!");
}
public void stop(){
this.flag = false;
} }
关于java - 优雅地结束基于控制台的多线程程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49950639/