1. 程式人生 > >使用Lock物件實現同步效果

使用Lock物件實現同步效果

Lock是一個介面,為了使用一個Lock物件,需要用到

  Lock lock = new ReentrantLock();  
與 synchronized (someObject) 類似的,lock()方法,表示當前執行緒佔用lock物件,一旦佔用,其他執行緒就不能佔用了。
與 synchronized 不同的是,一旦synchronized 塊結束,就會自動釋放對someObject的佔用。 lock卻必須呼叫unlock方法進行手動釋放,為了保證釋放的執行,往往會把unlock() 放在finally中進行。
使用Lock物件實現同步效果
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 package  multiplethread;   import  java.text.SimpleDateFormat; import  java.util.Date;
import  java.util.concurrent.locks.Lock; import  java.util.concurrent.locks.ReentrantLock;   public  class  TestThread {        public  static  String now() {          return  new  SimpleDateFormat( "HH:mm:ss" ).format( new  Date());      }        public  static  void  log(String msg) {          System.out.printf( "%s %s %s %n" , now() , Thread.currentThread().getName() , msg);      }        public  static  void  main(String[] args) {          Lock lock =  new  ReentrantLock();            Thread t1 =  new  Thread() {              public  void  run() {                  try  {                      log( "執行緒啟動" );                      log( "試圖佔有物件:lock" );                        lock.lock();                        log( "佔有物件:lock" );                      log( "進行5秒的業務操作" );                      Thread.sleep( 5000 );                    catch  (InterruptedException e) {                      e.printStackTrace();                  finally  {                      log( "釋放物件:lock" );                      lock.unlock();                  }                  log( "執行緒結束" );              }          };          t1.setName( "t1" );          t1.start();          try  {              //先讓t1飛2秒              Thread.sleep( 2000 );          catch  (InterruptedException e1) {              // TODO Auto-generated catch block              e1.printStackTrace();          }          Thread t2 =  new  Thread() {                public  void  run() {                  try  {                      log( "執行緒啟動" );                      log( "試圖佔有物件:lock" );                        lock.lock();                        log( "佔有物件:lock" );                      log( "進行5秒的業務操作" );                      Thread.sleep( 5000 );                    catch  (InterruptedException e) {                      e.printStackTrace();                  finally  {                      log( "釋放物件:lock" );                      lock.unlock();                  }                  log( "執行緒結束" );              }          };          t2.setName( "t2" );          t2.start();      }   }