如何正确停止线程?

背景

jdk1.2以前我们使用stop()停止一个线程,但是由于stop强制性的立即释放所有资源,非常不安全,1.2后这个方法已经不推荐使用,而后新加入interrupte()方法

interrupte()方法的使用

interrupte()方法会将线程的中断标志设置为true,但是这并不会让线程停止,它会继续正常执行,想让线程停止,我们需要在线程的run方法中加入对中断标志的检验,自行进行中断处理,因为,最了解自己的永远是自己,只有自己知道停止线程后该释放什么资源以达到优雅的退场的目的:

@Test
    public void interruptTest()
    {
        Thread thread1 = new Thread(() ->
        {
            for (int i = 1;; i++)
            {
                if (Thread.currentThread().isInterrupted())
                {
                    System.out.println("我中断了");
                    //释放资源
                    return;
                }
                System.out.println(i);
            }
        });
        thread1.start();
        System.out.println(Thread.currentThread().isInterrupted());
        try
        {
            Thread.sleep(100);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        thread1.interrupt();
    }

所以如何正确的停止线程? 非interrupte莫属,非自身处理莫属。

你可能感兴趣的:(Java多线程)