暂停线程suspend()和恢复线程resume()

1、使用suspend()方法暂停线程(挂起) : 运行->阻塞
2、使用resume()方法恢复线程 : 阻塞->就绪

suspend() 和 resume() 被用在等待另一个线程产生的结果的情 形:测试发现结果还没有产生后,让线程阻塞,另一个线程产生了结果后,调用 resume() 使其恢复。但suspend()方法很容易引起死锁问题, 已经不推荐使用了。

public class Run {
    public static void main(String[] args) {
        CountOperate c=new CountOperate();
        c.setName("ATest");
        try{
            c.start();
            Thread.sleep(5000);

            //暂停线程
            c.suspend();
            System.out.println("A="+System.currentTimeMillis()+" i= "+c.getI());
            Thread.sleep(5000);
            //暂停时,数据不会变化
            System.out.println("A="+System.currentTimeMillis()+" i= "+c.getI());

            //恢复线程
            c.resume();
            Thread.sleep(5000);

            //再次暂停线程
            c.suspend();
            System.out.println("B="+System.currentTimeMillis()+" i= "+c.getI());
            Thread.sleep(5000);
            //暂停时,数据不会变化
            System.out.println("B="+System.currentTimeMillis()+" i= "+c.getI());

        }catch (InterruptedException e){

        }
    }
}

结果:
A=1520323653691 i= 2121619071
//时间增加5000,但是数值不变
A=1520323658691 i= 2121619071
//再次暂停后启动,
B=1520323663692 i= 4345447893
B=1520323668692 i= 4345447893

2、suspend与resume方法的缺点—-独占
当某个线程的suspend()方法被调用时,该线程会被挂起。如果该线程占有了锁,则它不会释放锁。即,线程在挂起的状态下还持有锁。

线程被挂起,但是它的状态还是Runnable;

2.1、线程
public class CountOperate extends Thread {
    private long i=0L;
    public long getI() {
        return i;
    }
    public void setI(long i) {

        this.i = i;
    }
    public void run(){
        while(true){
            i++;
          //System.out.println(...),它是一个同步方法,需要先获得当前PrintStream对象的锁
          //System类中只有唯一的一个PrintStream对象
          //因此挂起之后,并不会释放该对象锁
            System.out.println(i);
        }
    }
}

2.2、执行
public class Run {
    public static void main(String[] args) {
        CountOperate c=new CountOperate();
        c.setName("ATest");
        try{
            c.start();
            Thread.sleep(5000);
            //暂停线程
            //suspend() 在导致线程暂停的同时,并不会去释放任何锁资源
            c.suspend();
      //导致main线程无法获得PrintStream对象锁,因此不能输出 
           System.out.println("A="+System.currentTimeMillis()+" i= "+c.getI());

        }catch (InterruptedException e){

        }
    }
}

3、suspend与resume方法的缺点—不同步
在使用suspend与resume方法时,容易出现因为线程的暂停而导致数据不同步的情况。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值