java ReadWriteLock接口

时间:2024-07-08 22:27:54
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockExample { private int value = 0; private final ReadWriteLock lock = new ReentrantReadWriteLock(); public void writeAndRead() { lock.writeLock().lock(); // 获取写锁 try { value++; System.out.println("Written value: " + value); lock.readLock().lock(); // 获取读锁 } finally { lock.writeLock().unlock(); // 释放写锁, 之后其他线程就可以获取读锁了 } try { Thread.sleep(10000); System.out.println("Read value after write: " + value); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { lock.readLock().unlock(); // 释放读锁 } } public int read() { lock.readLock().lock(); // 获取读锁 try { System.out.println("Read value: " + value); return value; } finally { lock.readLock().unlock(); // 释放读锁 } } public static void main(String[] args) throws InterruptedException { ReadWriteLockExample example = new ReadWriteLockExample(); // Writer thread Thread writerThread = new Thread(() -> { example.writeAndRead(); }); // Reader thread Thread readerThread = new Thread(() -> { example.read(); }); writerThread.start(); Thread.sleep(2000); readerThread.start(); } }