1. 程式人生 > >利用lock實現多執行緒同步

利用lock實現多執行緒同步

        我們不僅可以使用synchronized來實現多執行緒同步,還可以通過建立鎖物件來實現多執行緒的同步,還是上次模擬取現的操作,這次利用lock物件實現同步,下面是程式碼:

import java.util.concurrent.locks.ReentrantLock;


public class TestSyn {
   
	public static void main(String[] args) {
		 Account a =new Account(800);
		 WithDraw w1 = new WithDraw("取現1",a);
		 w1.start();
		 WithDraw w2 = new WithDraw("取現2",a);
		 w2.start();
	}
}
class WithDraw extends Thread
{
	Account a;
	
	public WithDraw(String name,Account a) {
		super(name);
		this.a = a;
	}

	public void run()
	{
	    a.withdraw(800)	;
	}
}
//定義一個賬戶類,用來模擬取現
class Account{
	int blance;
    
	//建立可重入鎖物件
	ReentrantLock lock = new ReentrantLock();
	
	public Account(int blance) {
		super();
		this.blance = blance;
	}

	public int getBlance() {
		return blance;
	}

	public void setBlance(int blance) {
		this.blance = blance;
	}
	//定義取款操作
	public  void withdraw(int money)
	{
		    //進行加鎖
		    lock.lock();
		    try{
			  if(money<=blance)
			  {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				setBlance(blance-money);
				System.out.println("取出"+money+"人民幣");
			  }
			  else
			  {
				 System.out.println("餘額不足,請確認");
			  }
		    }
		    finally
		    {
		    	lock.unlock();
		    }
		    
	}
}