关于java:java结束线程的三种方法

8次阅读

共计 1727 个字符,预计需要花费 5 分钟才能阅读完成。

java 罕用的完结一个运行中的线程的办法有 3 中:应用退出标记,应用 interrupt 办法,应用 stop 办法。

1. 应用退出标记

即在线程外部定义一个 bool 变量来判断是否完结以后的线程:

public class ThreadSafe extends Thread {
    public volatile boolean exit = false;
    public void run() {while (!exit){//do work}
    }

    public static void main(String[] args) throws Exception  {ThreadFlag thread = new ThreadFlag();  
        thread.start();  
        sleep(5000);  // 主线程提早 5 秒 
        thread.exit = true;   // 终止线程 thread 
        thread.join();  
        System.out.println("线程退出!");  
    }
}

这种状况个别是将线程的工作放在 run 办法中的一个 while 循环中,而由这个 bool 变量来对 while 循环进行管制。

2. 应用 interrupt 办法

这种办法须要判断以后的线程所处于的状态:
(1)以后线程处于阻塞状态时
线程处于阻塞状态个别是在应用了 sleep,同步锁的 wait,socket 中的 receiver,accept 等办法时,会使线程处于阻塞状态。

public class ThreadInterrupt extends Thread {public void run()  {  
        try {sleep(50000);  // 提早 50 秒 
        }  
        catch (InterruptedException e) {System.out.println(e.getMessage());  
        }  
    }  
    public static void main(String[] args) throws Exception  {Thread thread = new ThreadInterrupt();  
        thread.start();  
        System.out.println("在 50 秒之内按任意键中断线程!");  
        System.in.read();  
        thread.interrupt();  
        thread.join();  
        System.out.println("线程曾经退出!");  
    }  
}

留神这种状况写,应用 interrupt 办法完结线程的时候,肯定要先捕捉 InterruptedException 异样之后通过 break 来跳出循环,能力失常完结 run 办法。

(2)线程未处于阻塞状态时

应用 isInterrupted() 判断线程的中断标记来退出循环。当应用 interrupt() 办法时,中断标记就会置 true,和应用自定义的标记来管制循环是一样的情理。

public class ThreadSafe extends Thread {public void run() {while (!isInterrupted()) {   // 非阻塞过程中通过判断中断标记来退出
            try {Thread.sleep(5*1000);  // 阻塞过程捕捉中断异样来退出
            } catch (InterruptedException e) {e.printStackTrace();
                break;  // 捕捉到异样之后,执行 break 跳出循环
            }
        }
    }
}

3. 应用 stop 办法来完结线程

public class Main {public static void main(String[] args) throws InterruptedException {MyThread myThread = new MyThread();
        myThread.start();
        Thread.sleep(3000);   // 距离 3 秒后
        myThread.stop();      // 完结线程
        System.out.println("完结了");
 }
}

4. 完结办法的抉择

倡议应用 标记位 interrupt 办法 来完结线程,stop 办法曾经不倡议再被应用了。
因为 采纳 stop 是不平安的,次要影响点如下:

  1. thread.stop() 调用之后,创立子线程的线程就会抛出 ThreadDeatherror 的谬误;
  2. 调用 stop 会开释子线程所持有的所有锁。导致了该线程所持有的所有锁的忽然开释(不可管制),那么被爱护数据就有可能出现不一致性。
正文完
 0