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方法中就看到對象不一樣步 線程

相關文章
相關標籤/搜索