程序A:
public void startThreadPool2(boolean flag) {
while(flag) {
Runnable run = new Runnable() {
@Override
public void run() {
System.out.println("running");
}
};
service.execute(run);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
方案B:
public static void main(String[] args) {
SentimentAnalyse sentimentAnalyse = SentimentAnalyse.getInstance();
sentimentAnalyse.startThreadPool2(true);
}
程序C:
public static void main(String[] args) {
//how to stop the while loop
}
while 循环继续运行,我不知道如何在另一个程序中停止它。
//更新 你的方法也许都有效,我发现我的单例不工作,因为 Eclipse 在不同的程序中使用不同的类加载器。
最佳答案
将标志存储在 SentimentAnalyse 中并为其提供 setter ! 在程序 c(无论这是什么)中,您需要对在程序 b 中创建的 SentimentAnalyse 实例的引用。通过从程序 c 中使用 false 调用其 setter 来停止程序 a 中的循环
关于java - java中如何终止正在运行的循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27258890/