import java.lang.Thread;
import java.util.Scanner;
class Running extends Thread{
private boolean Run=true;
public void shutdown(){
Run=false;
}
public void run(){
while(Run){
for(int i=0;i<1000;i++){
System.out.println("Starting Counter:"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Volatile {
public static void main(String[] args) {
Running run1=new Running();
run1.start();
System.out.println("Press any key to stop thread execution");
Scanner sc=new Scanner(System.in);
sc.nextLine();
run1.shutdown();
}
}
我正在使用 volatile 关键字来停止线程执行。但无法得到解决方案
最佳答案
What should I be doing to stop the thread execution?
所以您的帖子提到了 volatile
关键字,但我在您发布的代码中没有看到它。您需要确保 Run
是一个 volatile boolean 值
,以便它可以在主线程中更改,并且其他线程将看到更改。
private volatile boolean Run=true;
但我认为问题在于您仅在外部 while
循环中测试此 Run
。也许您还希望在内部计数循环中使用它。像这样的东西:
for(int i = 0; i < 1000 && Run; i++) {
现在,一旦循环开始计数,它就必须在 Run
boolean 值被检查之前完成。那可能是 future 1000 秒。
关于java - 我应该怎么做才能停止线程执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21168879/