Java并发之ReentrantLock

来源:互联网 发布:openwrt防网络尖兵 编辑:程序博客网 时间:2024/05/08 00:55
package com.lxht.test;import com.lxht.emos.system.seqs.service.SystemSeqsService;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class TestReenTrantLock {     public static void main(String[] args) {         ReentrantLock reentLock = new ReentrantLock();   //创建ReentrantLock
         /**
           * 创建一个Condition;
           * Condition可以实现原来Object的wait(),和notify(),notifyAll()功能,但为什么要新增一个condition呢?
           * Condition比原来Object.wait()和Object.notify()功能更灵活,一个ReentrantLock可以创建多个Condition,这样不同的线程可以使用不同的Condition.awit(),
           * 这样可以灵活的实现部分线程的唤醒,而不用唤醒全部的线程;
         */
Condition condition = reentLock.newCondition();
         ReentrantThread thread1 = new ReentrantThread(reentLock,condition);     
         ReentrantThread thread2 = new ReentrantThread(reentLock,condition);     
         ReentrantThread thread3 = new ReentrantThread(reentLock,condition);    
         thread1.start();      
          thread2.start();     
          thread3.start();         
        try {          
           Thread.sleep(3000); 
        } catch (Exception e) {    
            e.printStackTrace();         
       }       
  try {           
          reentLock.lock();  //加锁,注意:多次调用lock()后需要调用配对的unlock()方法解锁, 如果当前Thread调用了2次lock(),则必须执行2次unlock()   
          System.out.println("singall all is running....");        
          condition.signalAll();  //唤醒condition上所有等待的Thread        
 } catch (Exception e) {           
     e.printStackTrace();        
  } finally {            
      reentLock.unlock(); //释放锁         
    }     
}
}  
class ReentrantThread extends Thread{    
     private ReentrantLock reentrantLock;    
    private Condition condition;    
   public ReentrantThread(ReentrantLock reentrantLock,Condition condition) {        
      this.reentrantLock = reentrantLock;       
     this.condition = condition;    
}    
public void run() {       
      int[] cc = new int[]{0,1,2};        try{           
       reentrantLock.lock();           
    for (int i : cc) {           
      System.out.println(this.getName() + ":" + i);          
    }         
      condition.await(); //当前Thread进入等待状态,这时会释放lock;            
      System.out.println("awiat is end....." + this.getName());       
  } catch (Exception e) {          
    e.printStackTrace();       
   } finally {               
     reentrantLock.unlock();            
 System.out.println("unlock," + this.getName());       
 }  
  }
}
原创粉丝点击