java读写锁
實現高并發情況下,多線程讀和讀不互斥,讀和寫互斥,寫和寫互斥,代碼如下:
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() {@Overridepublic void run() {while(true){queue.readData();}}}).start();}//開啟三個寫的線程for (int i = 0; i < 3; ++i) {new Thread(new Runnable() {@Overridepublic 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();} }?
轉載于:https://www.cnblogs.com/zhouquan-1992-04-06/p/6283549.html
總結
- 上一篇: Ch2 空间配置器(allocator)
- 下一篇: Flume Source 实例