suspend与resume

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

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

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线程了 this

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


2.可能形成不一样步例:
spa

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方法中就看到对象不一样步 线程

相关文章
相关标签/搜索