/* Read-write lock, read-read is not mutually exclusive, read-write is mutually exclusive, write-write is mutually exclusive Mutually exclusive in the same class */ import java.util.Random; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; publicclass ReadWriteLockTest { publicstaticvoid main(String[] args) { final Queue3 q3 = new Queue3(); for (inti = 0; i <3; i ++) { new Thread(){ publicvoid run(){ while(true){ q3.get(); } } }.start(); new Thread(){ publicvoid run(){ while(true){ q3.put(new Random().nextInt(10000)); } } }.start(); } } } class Queue3{ private Object data = null;//Shared data, only one thread can write the data, but multiple threads can read the data at the same time. ReadWriteLock rwl = new ReentrantReadWriteLock(); publicvoid get(){ rwl.readLock().lock(); try{ System.out.println(Thread.currentThread().getName() + " be ready to read data!"); Thread.sleep((long)(Math.random()*1000)); System.out.println(Thread.currentThread().getName() + "have read data :" + data); }catch(InterruptedException e){ e.printStackTrace (); }finally{ rwl.readLock().unlock(); } } publicvoid put(Object data){ rwl.writeLock().lock(); try{ System.out.println(Thread.currentThread().getName() + " be ready to write data!"); Thread.sleep((long)(Math.random()*1000)); this.data = data; System.out.println(Thread.currentThread().getName() + " have write data: " + data); }catch (InterruptedException e){ e.printStackTrace (); }finally{ rwl.writeLock().unlock(); } } } read-write lock cache import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class CacheDemo { private Map<String, Object> cache = new HashMap<String, Object>(); public static void main(String[] args) { } private ReadWriteLock rwl = new ReentrantReadWriteLock(); public Object getData(String key){ rwl.readLock().lock(); Object value = null; try{ value = cache.get(key); if(value == null){ rwl.readLock( ).unlock(); rwl.writeLock().lock(); try{ if(value==null){ value = "aaaa";//Actually lost queryDB(); } }finally{ rwl.writeLock().unlock(); } rwl.readLock().lock(); } }finally{ rwl.readLock().unlock(); } return value; } }
Read-write lock for multi-threaded concurrent threads
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326487459&siteId=291194637
Ranking