如何终止线程 有没有什么命令可以直接终止线程的thread.stop() api上写了不建议使用,那改用什么命令呢 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 为了降低死锁的发生几率,Java 2放弃了Thread类stop( ),suspend( )和resume( )方法。 之所以要放弃stop( )是因为,它不会释放对象的锁,因此如果对象正处于无效状态(也就是被破坏了),其它线程就可能会看到并且修改它了。这个问题的后果可能非常微秒,因此难以察觉。所以别再用stop( )了,相反你应该设置一个旗标(flag)来告诉线程什么时候该停止。下面是一个简单的例子://: c13:Stopping.java// The safe way to stop a thread.import java.util.*;class CanStop extends Thread { // Must be volatile: private volatile boolean stop = false; private int counter = 0; public void run() { while(!stop && counter < 10000) { System.out.println(counter++); } if(stop) System.out.println("Detected stop"); } public void requestStop() { stop = true; }}public class Stopping { public static void main(String[] args) { final CanStop stoppable = new CanStop(); stoppable.start(); new Timer(true).schedule(new TimerTask() { public void run() { System.out.println("Requesting stop"); stoppable.requestStop(); } }, 500); // run() after 500 milliseconds }} ///:~ stop必须是volatile的,这样才能确保run( )方法能看到它(否则它会使用本地的缓存值)。这个线程的"任务"是打印10,000个数字,所以当counter >= 10000或有人要它停下来的时候,它就结束了。注意requestStop( )不是synchronized,因为stop既是boolean(改成true是一个原子操作)又是volatile的。main( )启动完CanStop之后设置了一个Timer,让它过半秒自动调用requestStop( )。Timer的构造函数里的true参数的任务是,把这个线程设成守护线程,这样它就不会阻止程序退出了。 java 调用 Matlab出错 java 画图 applet怎样连接本地网页(没上网) struts配置环境需要什么啊?? 如题 !!!一个非常奇怪的问题!!!!!!!!!!!!!!!! 怎样设置classpath? 来者有分,下载文件我这么做对吗? 帮我一把吧:怎么在applet下载服务器上的文件? JFileChooser怎么选择目录而不是文件 servlet/jsp的配置问题 想替换路径中的"\"为"/" 执行一直出错path.replaceAll("\\","/");
// The safe way to stop a thread.
import java.util.*;
class CanStop extends Thread {
// Must be volatile:
private volatile boolean stop = false;
private int counter = 0;
public void run() {
while(!stop && counter < 10000) {
System.out.println(counter++);
}
if(stop)
System.out.println("Detected stop");
}
public void requestStop() { stop = true; }
}
public class Stopping {
public static void main(String[] args) {
final CanStop stoppable = new CanStop();
stoppable.start();
new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("Requesting stop");
stoppable.requestStop();
}
}, 500); // run() after 500 milliseconds
}
} ///:~
stop必须是volatile的,这样才能确保run( )方法能看到它(否则它会使用本地的缓存值)。这个线程的"任务"是打印10,000个数字,所以当counter >= 10000或有人要它停下来的时候,它就结束了。注意requestStop( )不是synchronized,因为stop既是boolean(改成true是一个原子操作)又是volatile的。main( )启动完CanStop之后设置了一个Timer,让它过半秒自动调用requestStop( )。Timer的构造函数里的true参数的任务是,把这个线程设成守护线程,这样它就不会阻止程序退出了。