Java多线程如何在程序安全的情况下关闭?

解决方案 »

  1.   

    我是读取一个文件的内容到另一个日志文件里面的,现在总是在stop以后日志文件里面保存的内容不完全.
      

  2.   

    想安全停止不推荐调用stop()和interrupt()
    使用楼上的
         while(flag){
            .....
            if(条件)flag =false;
         }这样的方法结束线程就好了
      

  3.   

     Thread.stop、Thread.suspend 和 Thread.resume 等方法即为不安全推出线程的方法,一般是不推荐使用的。
    可以用定义Boolean参数的方法,然后控制循环的办法:
    import java.util.*;
    public class TestInterrupt {
      public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
        try {Thread.sleep(10000);}
        catch (InterruptedException e) {}
        thread.flag=false;
      }
    }class MyThread extends Thread {
    boolean flag = true;
      public void run(){
        while(flag){
          System.out.println("==="+new Date()+"===");
          try {
            sleep(1000);
          } catch (InterruptedException e) {
            return;
          }
        }
      }
    }其实还可以更加完善,即:专门定义一个flag的参数类,然后用tread.className调用之,更加完善