public class ReadWriteLockDemo { public static void main(String[] args) { final Queue q = new Queue(); for (int i = 0; i < 3; i++) { new Thread(new Runnable(){ @Override public void run() { while (true) { q.set(new Random().nextInt(1000)); } } }).start(); new Thread(new Runnable() { @Override public void run() { while (true) { q.read(); } } }).start(); } } } class Queue{ private int data; private ReadWriteLock rwl = new ReentrantReadWriteLock(); public void set(int data){ rwl.readLock().lock(); this.data = data; try { System.out.println(Thread.currentThread().getName() + " ready to write data"); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + " 写入数据 " + data); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ rwl.readLock().unlock(); } } public void read() { rwl.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + " ready to read data"); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + " 获取dao数据 " + data); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ rwl.writeLock().unlock(); } } }
ReadWriteLock 读和写锁
时间: 2024-10-01 02:51:59