線程問題

線程問題java

線程鎖爲threadNo,每一個線程threadNo惟一,達不到互斥最後資源recources不能同步this

package len_server;

public class ThreadTest2 extends Thread {

  
	private  String threadNo;
	private  String lock;   

	private static int recources=100;//須要同步的資源對象   
 
	public ThreadTest2(String threadNo,String lock) {   
		this.threadNo = threadNo;  
		this.lock=lock;
	}   
	
	public static void main(String[] args) throws InterruptedException {
		for (int i = 1; i <=3; i++) {   
			ThreadTest2 t=new ThreadTest2(String.valueOf(i),"abc");
		    t.start();   
		 }
		sleep(2000);
		System.out.println("=================================");
		System.out.println(recources);//打印結果
	}
   
    public void run() {
    	
    	synchronized (this.getThreadNo()) {
    		int flag=recources;  //模擬查詢餘額
    		try {
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    		recources=flag+1;//模擬存款
		}
    	
    }
    
    

	public String getThreadNo() {
		return threadNo;
	}
	public void setThreadNo(String threadNo) {
		this.threadNo = threadNo;
	}
	public String getLock() {
		return lock;
	}
	public void setLock(String lock) {
		this.lock = lock;
	}
}

線程鎖爲lock,每一個線程的lock相同,也就是鎖對象相同能實現資源同步線程

package len_server;

public class ThreadTest2 extends Thread {

  
	private  String threadNo;
	private  String lock;   

	private static int recources=100;//須要同步的資源對象   
 
	public ThreadTest2(String threadNo,String lock) {   
		this.threadNo = threadNo;  
		this.lock=lock;
	}   
	
	public static void main(String[] args) throws InterruptedException {
		for (int i = 1; i <=3; i++) {   
			ThreadTest2 t=new ThreadTest2(String.valueOf(i),"abc");
		    t.start();   
		 }
		sleep(2000);
		System.out.println("=================================");
		System.out.println(recources);//打印結果
	}
   
    public void run() {
    	
    	synchronized (this.getLock()) {
    		int flag=recources;  //模擬查詢餘額
    		try {
				sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    		recources=flag+1;//模擬存款
		}
    	
    }
    
    

	public String getThreadNo() {
		return threadNo;
	}
	public void setThreadNo(String threadNo) {
		this.threadNo = threadNo;
	}
	public String getLock() {
		return lock;
	}
	public void setLock(String lock) {
		this.lock = lock;
	}
}

猜猜分別輸出結果?code

相關文章
相關標籤/搜索