编程语言
首页 > 编程语言> > 如何中止Java中的线程

如何中止Java中的线程

作者:互联网

如何中止一个运行中的线程

Java作为第一款官方声明支持多线程的编程语言,其早期提供的一些Api并不是特别的完善,所以可以看到Thread类中的一些早期方法都已经被标记上过时了,例如stop、resume,suspend,destory方法都被标记上过时的标签。那为了弥补这些缺失的功能,后续的Java提供了interrupt这样的方法。

通过interrupt()来中止一个线程

stop方法会立即中止线程的运行并抛出异常,同时释放所有的锁,这可能产生数据安全问题(https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html)。interrupt方法的实现方式更类似于给线程发送了一个信号(简单的理解为给线程设置了一个属性来标记是否应当停止当前线程),线程接收到信号之后具体如何处理,是中止线程还是正常运行取决于运行的线程的具体逻辑。

一个线程中止的最佳实践:

public class StandardInterrupt extends Thread{
    public static void main(String[] args) throws InterruptedException {
        StandardInterrupt standardInterrupt = new StandardInterrupt();
        System.out.println("main thread --> start running");
        standardInterrupt.start();
        Thread.sleep(3000);
        System.out.println("main thread --> aiting for signal");
        standardInterrupt.interrupt();
        Thread.sleep(3000);
        System.out.println("main thread --> stop application");
    }

    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            System.out.println("active thread --> i am working");
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                System.out.println("active thread --> detective interrupt");
                System.out.println("active thread --> check the signal: " +Thread.currentThread().isInterrupted());
                Thread.currentThread().interrupt();
            }
        }
        System.out.println("active thread --> finish my working");
    }
}

//输出
main thread --> start running
active thread --> i am working
active thread --> i am working
active thread --> i am working
main thread --> aiting for signal
active thread --> detective interrupt
active thread --> check the signal: false
active thread --> finish my working
main thread --> stop application

standardInterrupt.interrupt(); 告知active thread应该停止运行了。但是

标签:Java,Thread,thread,中止,--,interrupt,线程,active
来源: https://www.cnblogs.com/Pikzas/p/13725821.html