实现高并发情况下,多线程读和读不互斥,读和写互斥,写和写互斥,代码如下:
package threadLock; import java.util.Random; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriterLockTest { public void init() { final Queue queue = new Queue(); //开启三个读的线程 for (int i = 0; i < 3; ++i) { new Thread(new Runnable() { @Override public void run() { while(true){ queue.readData(); } } }).start(); } //开启三个写的线程 for (int i = 0; i < 3; ++i) { new Thread(new Runnable() { @Override public void run() { while(true) queue.writerData(); } }).start(); } } class Queue { private Integer data; // 多线程操作的资源 ReadWriteLock rwl = new ReentrantReadWriteLock(); //读写锁,读和读不互斥,读和写互斥,读和读互斥 public void readData() { try { rwl.readLock().lock(); //上读锁,线程只能做读操作 System.out.println(Thread.currentThread().getName() + " ready to read"); Thread.sleep(300); System.out.println(Thread.currentThread().getName() + "has read data is " + data); } catch (InterruptedException e) { e.printStackTrace(); }finally{ rwl.readLock().unlock(); //释放读锁 } } public void writerData() { try { rwl.writeLock().lock(); //上写锁,只能当前线程执行 System.out.println(Thread.currentThread().getName() + " ready to write"); Thread.sleep(300); this.data = new Random().nextInt(10000); System.out.println(Thread.currentThread().getName() + "has write data is " + data); } catch (InterruptedException e) { e.printStackTrace(); }finally{ rwl.writeLock().unlock(); //释放写锁 } } } public static void main(String[] args) { new ReadWriterLockTest().init(); } }