有没有什么命令可以直接终止线程的
thread.stop() api上写了不建议使用,那改用什么命令呢

解决方案 »

  1.   

    为了降低死锁的发生几率,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参数的任务是,把这个线程设成守护线程,这样它就不会阻止程序退出了。