The Lock method is more object-oriented than the synchronized Method in the traditional thread model. Similar to the Lock in life, the Lock itself should also be an object. The code snippets executed by two threads must use the same Lock object to implement synchronization and mutual exclusion.
Read/write locks: read/write locks are divided into read/write locks. Multiple read locks are not mutually exclusive. The read/write locks are mutually exclusive and are controlled by the jvm. You only need to apply the corresponding locks. If your code read-only data can be read by many people at the same time but cannot be written at the same time, read the lock. If your code modifies data, only one person can write it, and cannot be read at the same time, then write the lock. In short, read locks are applied during reading and write locks when writing!
Queue3 q3 = ( i=0;i<3;i++ ( ( i=0;i<3;i++ ( q3.put( Random().nextInt(10000 Object data = ; ReentrantReadWriteLock rwl = rwl.readLock().lock(); System.out.println(Thread.currentThread().getName() + " be ready to read data!" Thread.sleep(()(Math.random()*1000 } System.out.println(Thread.currentThread().getName() + "have read data :" + rwl.readLock().unlock(); rwl.writeLock().lock(); System.out.println(Thread.currentThread().getName() + " be ready to write data!" Thread.sleep(()(Math.random()*1000 } .data = System.out.println(Thread.currentThread().getName() + " have write data: " + rwl.writeLock().unlock(); }
Thread-0 be ready to read data!-1 be ready to read data!-2 be ready to read data!-0have read data :-2have read data :-1have read data :-5 be ready to write data!-5 have write data: 6934-5 be ready to write data!-5 have write data: 8987-5 be ready to write data!-5 have write data: 8496
Map<String, Object> map = HashMap<String, Object>(); ReadWriteLock rwl = Object value = rwl.readLock().lock(); value = (value == ){ (value == value = "aaa"; } rwl.writeLock().unlock(); rwl.readLock().lock(); } rwl.readLock().unlock(); }