嗨我正在使用下一个代码来尝试停止一个线程,但是当我看到Running为false时它再次成为现实.
public class usoos {
public static void main(String[] args) throws Exception {
start();
Thread.sleep(10000);
end();
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(){
System.out.println("finished.");
start().shutdown();
}
}
Run Code Online (Sandbox Code Playgroud)
和线程
public class SimpleThreads extends Thread {
volatile boolean running = true;
public SimpleThreads () {
}
public void run() {
while (running){
System.out.println("Running = " + running);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread" + "======Running = " + running);
}
public void shutdown(){
running = false;
System.out.println("End" );
}
}
Run Code Online (Sandbox Code Playgroud)
问题是当我试图阻止它时(我将运行设置为false),它会再次启动..
在end方法中查看以下行:
start().shutdown();
Run Code Online (Sandbox Code Playgroud)
你没有停止原始实例; 你正在开始另一个,然后你立即关闭.
您start和end方法之间没有任何关联- 没有信息,没有参考从一个传递到另一个.显然不可能停止在start方法中启动的线程.
你的end方法不应该static; 事实上,你甚至不需要它,shutdown已经是它了:
SimpleThreads t = start();
Thread.sleep(10000);
t.shutdown();
Run Code Online (Sandbox Code Playgroud)