美文网首页
2.0 暂停、恢复线程

2.0 暂停、恢复线程

作者: MC_Honva | 来源:发表于2018-04-08 17:51 被阅读11次

    Java 中可以使用suspend()方法来暂停线程运行,通过resume()方法来恢复线程执行

    public class MyThread extends Thread {
        private long i;
    
        public long getI() {
            return i;
        }
    
        public void setI(long i) {
            this.i = i;
        }
    
        @Override
        public void run() {
            while (true) {
                i++;
            }
        }
    
    }
    
    public class Run {
        public static void main(String[] args) {
            try {
                MyThread thread = new MyThread();
                thread.start();
                Thread.sleep(2000);
                //A段
                thread.suspend();
                System.out.println("A="+System.currentTimeMillis()+",i="+thread.getI());
                Thread.sleep(2000);
                System.out.println("A="+System.currentTimeMillis()+",i="+thread.getI());
                //B段
                thread.resume();
                Thread.sleep(2000);
                System.out.println("B="+System.currentTimeMillis()+",i="+thread.getI());
                Thread.sleep(2000);
                //C段
                thread.suspend();
                System.out.println("C="+System.currentTimeMillis()+",i="+thread.getI());
                Thread.sleep(2000);
                System.out.println("C="+System.currentTimeMillis()+",i="+thread.getI());
                
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    

    显然,方法suspend和resume都是已经被废弃的方法

    suspend()和resume()缺点

    容易造成公共同步对象的独占

    对于添加了同步锁的对象,如果在该方法中调用了suspend()方法,将导致对象锁无法释放,其他线程无法访问的问题。

    相关文章

      网友评论

          本文标题:2.0 暂停、恢复线程

          本文链接:https://www.haomeiwen.com/subject/fjsmhftx.html