你需要实现一个高效的缓存,它允许多个用户读,但只允许一个用户写,以此来保持它的完整性,你会怎样去实现它?
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 }
运行结果如下: