关于Thread对象的suspend,resume,stop方法

一、作用

    对于老式得磁带录音机,上面都会有,暂停,继续,停止。Thread中suspend,resume,stop方法就类似。

    suspend,使线程暂停,但是不会释放类似锁这样的资源。

    resume,使线程恢复,如果之前没有使用suspend暂停线程,则不起作用。

    stop,停止当前线程。不会保证释放当前线程占有的资源。

二、代码

public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i <= 10000; i ++) {
                System.out.println(i);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();

    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    thread.suspend();                       //注释1
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    thread.resume();                        //注释2
    try {
        TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    thread.stop();                        //注释3
    System.out.println("main end..");

}


    代码中注释1的地方,线程会暂停输出,直到注释2处才恢复运行,到了注释3的地方,线程就被终止了。

    suspend,resume,stop这样的方法都被标注为过期方法,因为其不会保证释放资源,容易产生死锁,所以不建议使用。

三、如何安全的暂停一个线程

使用一个volatile修饰的boolean类型的标志在循环的时候判断是否已经停止。

public class Test {
    public static void main(String[] args) {
        Task task = new Task();
        new Thread(task).start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        task.stop();
        System.out.println("main end...");
    }

    static class Task implements Runnable {
        static volatile boolean stop = false;

        public void stop() {
            stop = true;
        }

        @Override
        public void run() {
            int i = 0;
            while (!stop) {
                System.out.println(i++);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

    


转载于:https://my.oschina.net/u/2250599/blog/617312

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值