Lock讀寫鎖機制可以實現!
在Java中Lock接口比synchronized塊的優勢是什么?
Lock接口最大的優勢是為讀和寫分別提供了鎖。
1 import java.text.SimpleDateFormat; 2 import java.util.Date; 3 import java.util.Random; 4 import java.util.concurrent.locks.ReadWriteLock; 5 import java.util.concurrent.locks.ReentrantReadWriteLock; 6 7 8 9 10 public class JoinTest2 { 11 12 public static void main(String[] args) { 13 final TheData theData = new TheData(); 14 for(int i=0;i<4;i++){ 15 new Thread(new Runnable() { 16 @Override 17 public void run() { 18 theData.get(); 19 } 20 }).start(); 21 } 22 for(int i=0;i<4;i++){ 23 new Thread(new Runnable() { 24 @Override 25 public void run() { 26 theData.put(new Random().nextInt(1000)); 27 } 28 }).start(); 29 } 30 } 31 32 33 } 34 35 class TheData{ 36 private Integer data = 0; 37 private ReadWriteLock rwLock = new ReentrantReadWriteLock(); 38 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 39 public void get(){ 40 rwLock.readLock().lock();//讀鎖開啟,讀進程均可進入 41 try{//用try finally來防止因異常而造成的死鎖 42 System.out.println(Thread.currentThread().getName()+"read lock is ready.."+sdf.format(new Date())); 43 Thread.sleep(1000); 44 System.out.println(Thread.currentThread().getName()+"read data is"+data); 45 }catch (InterruptedException e) { 46 e.printStackTrace(); 47 }finally{ 48 rwLock.readLock().unlock();//讀鎖解鎖 49 } 50 } 51 52 public void put(Integer data){ 53 rwLock.writeLock().lock();//寫鎖開啟,這時只有一個寫線程進入 54 try{//用try finally來防止因異常而造成的死鎖 55 System.out.println(Thread.currentThread().getName()+"write lock is ready.."+sdf.format(new Date())); 56 Thread.sleep(1000); 57 this.data = data; 58 System.out.println(Thread.currentThread().getName()+"write data is"+data); 59 60 }catch (InterruptedException e) { 61 e.printStackTrace(); 62 }finally{ 63 rwLock.writeLock().unlock();//寫鎖解鎖 64 } 65 } 66 }
運行結果如下: