java多线程之suspend(),resume()和stop()方法

1:方法介绍

  1. suspend():暂停任务
  2. resume():恢复任务
  3. stop():停止任务

  不推荐在使用这三个方法已suspend方法为例,在调用后,线程不会释放已经占有的资源比如锁,而是带着资源进入睡眠状态,十分容易引发死锁。同样stop方法在终结一个线程时,不能保证线程资源的正常释放,通常灭有基于线程完成资源释放的机会。

 2:如何优雅的终止或者暂停线程尼?

package concurrencyTest4_2_5;

import java.util.concurrent.TimeUnit;

/**
 * @author :dazhu
 * @date :Created in 2020/4/8 17:22
 * @description:避免使用suspend,resume和stop,如何优雅的暂停和恢复线程尼?
 * @modified By:
 * @version: $
 */
public class ShutDown {
    public static void main(String[]args) throws Exception{
        Runner one = new Runner();
        Thread countThread = new Thread(one,"CountThread");
        countThread.start();
        //main线程睡眠1s
        TimeUnit.SECONDS.sleep(1);

        //通过interrupt方法来停止该线程
        countThread.interrupt();
        Runner two = new Runner();
        countThread = new Thread(two,"CountThread");
        countThread.start();

        //main线程睡眠1秒,main线程对Runner two 进行取消,使得CountThread能够感知到on为false而结束
        TimeUnit.SECONDS.sleep(1);
        //通过调用cancel方法来停止该线程
        two.cancel();
    }

    private static class Runner implements Runnable{
        private long i;
        private volatile boolean on = true;
        @Override
        public void run(){
            System.out.println("进入run方法");
            while(on&&!Thread.currentThread().isInterrupted()){
                i++;
            }
            System.out.println("Count i = " +i);
            System.out.println("run方法结束");
            System.out.println("*************");
        }

        public void cancel(){
            on = false;
        }
    }
}

  使用中断方法或者cancel标志位方法都有机会让线程取释放自己占有的资源,这种方法更安全和优雅。

猜你喜欢

转载自www.cnblogs.com/dazhu123/p/12661229.html