[英]Trying to stop thread, but it start again
嗨,我正在使用下一个代码尝试停止线程,但是当我看到Running为false时,它将再次变为true。
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();
}
}
和线程
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" );
}
}
问题是当我尝试停止它(我将运行设置为false)时,它将再次启动。
在end
方法中查看以下行:
start().shutdown();
您没有停止原始实例; 您正在启动另一个,然后立即将其关闭。
您的start
和end
方法之间没有联系-没有信息,没有引用从一个传递到另一个。 显然不可能停止您在start
方法中start
的线程。
您的end
方法不应该是static
; 实际上,您甚至不需要它,已经shutdown
了:
SimpleThreads t = start();
Thread.sleep(10000);
t.shutdown();
因为在end
方法中,您只是创建了一个新Thread
并杀死它,所以保存线程实例并杀死它:
您的代码应如下所示:
public class usoos {
public static void main(String[] args) throws Exception {
SimpleThreads id = start();
Thread.sleep(10000);
end(id);
}
public static SimpleThreads start(){
SimpleThreads id = new SimpleThreads();
id.start();
System.out.println("started.");
return id;
}
public static void end(SimpleThreads id){
System.out.println("finished.");
id.shutdown();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.