suspend与resume

suspend与resume是一对暂停和唤醒的方法。

1.使用suspend不当会造成公共的同步对象的独占,例:

public static class CommonObject{
		synchronized public void printString(){
			if(Thread.currentThread().getName().equals("a")){
				System.out.println("当前为线程a,并且suspend a线程了");
				Thread.currentThread().suspend();
			}else{
				System.out.println("其他线程");
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final CommonObject commonObject = new CommonObject();
		
		 new Thread("a"){
			 @Override
			 public void run() {
				 commonObject.printString();
			 };
		}.start();
		
		Thread.sleep(500);
		
		new Thread("b"){
			@Override
			public void run() {
				commonObject.printString();
			};
		}.start();
	}
结果:

当前为线程a,并且suspend a线程了

输出分析:可以得知线程a在公共对象的同步方法中使用suspend,导致公共对象commonObject的 printString方法被a独占。致使b线程无法使用printString方法,直到a线程执行完printString


2.可能造成不同步例:

public static class CommonObject{
		private String name = "无";
		private int age = -1;
		synchronized public void setProperty(String name,int age){
			this.name = name;
			if(Thread.currentThread().getName().equals("a")){
				Thread.currentThread().suspend();
			}
			this.age = age;
		}
		public void printProperty(){
			System.out.println("name= "+name+" age= "+age);
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		final CommonObject commonObject = new CommonObject();
		
		 new Thread("a"){
			 @Override
			 public void run() {
				 commonObject.setProperty("张三",25);
			 };
		}.start();
		
		Thread.sleep(100);
		
		commonObject.printProperty();
		
	}



输出结果:
name= 张三 age= -1

输出分析:线程a在设置属性过程中中断了,导致"年龄"属性没有设置,结果在main方法中就看到对象不同步









转载于:https://my.oschina.net/u/2552286/blog/667920

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值