Graceful Java Programming 优雅Java编程 之 一个经典的线程锁

功能:
1.实现跨客户端的多用户同步锁
2.实现多重嵌套的同步锁
说明:
      这是本人7年Java生涯以来最钟爱的一段Java代码,其结构简洁,设计优雅,充分显示了作者对Java多线程机制的领悟;更重要的它可以很轻量级的嵌入到任何类的任何方法的任何代码段,来实现该代码段的线程同步。实在是经典中的经典啊!
public class TransactionLock {
 //并发事务锁对象,根据lockOwner,判定相应线程能否获得事务锁
 private Thread lockOwner = null;
 
 //锁深度,在同一synchronized事务内,事务锁被获取的次数
 private int lockDeep = 0;
 
 
 public TransactionLock() {
  super();
 }
 public synchronized void getLock(){
  while(tryGetLock() == false){
   try {
    this.wait();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 private synchronized boolean tryGetLock(){
  boolean rtval = false;
  
  if(this.lockOwner == null){
   this.lockOwner = Thread.currentThread();
   this.lockDeep = 1;
   rtval = true;
  }else if(this.lockOwner == Thread.currentThread()){
   this.lockDeep += 1;
   rtval = true;
  }
  
  return rtval;
 }
 
 public synchronized void freeLock(){
  if(this.lockOwner == Thread.currentThread()){
   this.lockDeep -= 1;
   if(this.lockDeep == 0){
    this.lockOwner = null;
    this.notify();
   }
  }
 }
 
 public Thread getLockOwner(){
  return this.lockOwner;
 }
 
 public synchronized boolean hasLocked(){
  return (tryGetLock() == false);
 } 
 
}

你可能感兴趣的:(java,多线程,thread,编程,活动)