ReentrantReadWriteLock
使用ReentrantLock构建简单的读写锁
package com.dwz.locks; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class ReadWriteLockExample { private final static ReentrantLock lock = new ReentrantLock(); private final static List<Long> data = new ArrayList<>(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(ReadWriteLockExample::write); thread1.start(); TimeUnit.SECONDS.sleep(1); Thread thread2 = new Thread(ReadWriteLockExample::read); thread2.start(); } public static void write() { try { lock.lock(); data.add(System.currentTimeMillis()); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void read() { try { lock.lock(); data.forEach(System.out::println); TimeUnit.SECONDS.sleep(5); System.out.println(Thread.currentThread().getName() + "===================="); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } }
使用ReentrantReadWriteLock
package com.dwz.locks; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 使用ReentrantReadWriteLock解决读写安全问题以及同时读不需要加锁问题 * * write write false * write read false * read write false * read read true */ public class ReadWriteLockExample2 { private final static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final static Lock readLock = readWriteLock.readLock(); private final static Lock writeLock = readWriteLock.writeLock(); private final static List<Long> data = new ArrayList<>(); public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(ReadWriteLockExample::read); thread1.start(); TimeUnit.SECONDS.sleep(1); Thread thread2 = new Thread(ReadWriteLockExample::read); thread2.start(); } public static void write() { try { writeLock.lock(); data.add(System.currentTimeMillis()); TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } finally { writeLock.unlock(); } } public static void read() { try { readLock.lock(); data.forEach(System.out::println); TimeUnit.SECONDS.sleep(5); System.out.println(Thread.currentThread().getName() + "===================="); } catch (InterruptedException e) { e.printStackTrace(); } finally { readLock.unlock(); } } }