日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java读写锁

發布時間:2024/4/14 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

總結

以上是生活随笔為你收集整理的java读写锁的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。