java ReentrantLock 使用
生活随笔
收集整理的這篇文章主要介紹了
java ReentrantLock 使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.ReentrantLock? 簡單的使用
private Lock lock = new ReentrantLock();
lock.lock();用來獲取鎖。
lock.unlock();用來釋放鎖
2.使用?ReentrantLock 實現生產者和消費者
package com.qey.lock;import javax.sound.midi.Soundbank; import java.util.ArrayList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;/*** @ClassName ConditionBuffer* @Description volte* @Author* @Date 2020-05-13 15:44* @Version 1.1**/ public class ConditionBuffer implements Buffer {private Lock lock = new ReentrantLock();private Condition put = lock.newCondition();private Condition take = lock.newCondition();private final static int CAPACITY = 1;private ArrayList<Integer> arrayList = new ArrayList<>(CAPACITY);private int count = -1;public ArrayList<Integer> getArrayList() {return arrayList;}@Overridepublic void put(Integer integer) throws InterruptedException {if (integer == null) {return;}lock.lock();try {while (count == CAPACITY) {put.await();System.out.println("ReentantLock put "+ Thread.currentThread().getName());}arrayList.add(integer);count++;take.signal();} catch (InterruptedException e) {e.printStackTrace();}finally {lock.unlock();}}@Overridepublic Integer take() throws InterruptedException {lock.lock();while (count == 0) {take.await();System.out.println("ReentantLock take "+ Thread.currentThread().getName());}try {Integer o = arrayList.get(count % CAPACITY);count--;put.signal();return o;} finally {lock.unlock();}}static class RunnableTake implements Runnable{private Buffer buffer;public RunnableTake(Buffer buffer) {this.buffer = buffer;}@Overridepublic void run() {try {while (true){buffer.take();}} catch (InterruptedException e) {e.printStackTrace();}}}static class RunnablePut implements Runnable{private Buffer buffer;public RunnablePut(Buffer buffer) {this.buffer = buffer;}@Overridepublic void run() {try {while (true){buffer.put(1);}} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {ConditionBuffer conditionBuffer = new ConditionBuffer();Thread thread1 = new Thread(new RunnablePut(conditionBuffer));thread1.start();Thread thread2 = new Thread(new RunnableTake(conditionBuffer));thread2.start();} }后續補充:ReentrantReadWriteLock??多線程并發之讀寫鎖(ReentranReadWriteLock&ReadWriteLock)使用詳解_小小默:進無止境-CSDN博客
參考:Java ReentrantLock中condition通信的好處 - 簡書
? ? ? ??JAVA中的ReentrantLock和ReentrantReadWriteLock鎖簡單使用_madman-CSDN博客_reentrantreadwritelock使用
總結
以上是生活随笔為你收集整理的java ReentrantLock 使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos 配置php开发环境变量配置
- 下一篇: java竖向菜单,垂直滑动菜单