java之Thread(2): start,run,stop,suspend,resume,stop,destroy

    

run方法:

  1. 不是Runnable里面的,不一样。thread的run方法,是用来调用runnable里面的target,如果不是使用Runnable, 那么就返回空。

  2. public synchronized void start() {
            /**
             * This method is not invoked for the main method thread or "system"
             * group threads created/set up by the VM. Any new functionality added
             * to this method in the future may have to also be added to the VM.
             *
             * A zero status value corresponds to state "NEW".
             */
            if (threadStatus != 0)
                throw new IllegalThreadStateException();
    
            /* Notify the group that this thread is about to be started
             * so that it can be added to the group's list of threads
             * and the group's unstarted count can be decremented. */
            group.add(this);
    
            boolean started = false;
            try {
                start0();
                started = true;
            } finally {
                try {
                    if (!started) {
                        group.threadStartFailed(this);
                    }
                } catch (Throwable ignore) {
                    /* do nothing. If start0 threw a Throwable then
                      it will be passed up the call stack */
                }
            }
        }

     

thread的stop,resume, suspend,destroy方法有风险,所以已经配标记为弃用。

此方法原来被设计为破坏线程,在没有清理的情况下。这时,这个线程所有的监视器都会保持锁的状态,然后,这个方法从来没有实现过。如果被实现了,肯定是有很大概率造成死锁。因为没有释放资源。

这个方法仅仅是和suspend一起用而存在,这里值得探讨。

ThreadDeath就是一个异常,会一致传播到堆栈里面,被虚拟机捕获,杀死现在的线程,这样就会将所有的这个线程占据的监视器和锁释放,造成不可预估的情况。

说不安全,关键就在于不可预估,所以安全的方式是可以预估的暂停。比如使用信号量(就是线程执行根据一个变量的值来判断是否执行),其他的wait,yield,sleep都是可控的。

java对于这几个方法标为弃用的原因的文档:

https://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

 

有两点需要注意一下:

首先是stop的代替方法最好是使用一个变量。

另外,如果目标线程已经等了很长时间取等待,那么应该调用interrupt来中断等待。

private volatile Thread blinker;

   // jdk文档建议的取代stop方法。
    public void stop() {
        blinker = null;
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (blinker == thisThread) {
            try {
                thisThread.sleep(interval);
            } catch (InterruptedException e){
            }
            repaint();
        }
    }

suspend和resume就是类似wait和notify,但是容易造成死锁。因为resume的线程在resume之前请求suspend锁着的资源。wait不会,因为wait释放资源。

使用interrupt用来结束长时间等待的线程。

interrupt还需要再研究。

Reference: 

多线程的一个参考:

https://blog.csdn.net/pange1991/article/details/53860651

native的方法: https://www.cnblogs.com/b3051/p/7484501.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值