JavaSE-多线程(2.2)- 锁举例2(Reentrant Lock )

本文介绍了使用Java ReentrantLock进行多线程同步的示例,重点讲解了自定义容器如何通过CAS实现并发控制,以及put和get操作的线程安全实现。通过实例演示了如何避免死锁和资源竞争,提高并发性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JavaSE-多线程(2.2)- 锁举例2(Reentrant Lock )

Reentrant Lock 基于CAS

package com.hs.example.base.multithread.day01;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 自定义容器,固定容量最大值为MAX_COUNT,运行多线程并发put和get
 *
 * @param <T>
 */
public class ReentrantLock4<T> {

    private Lock lock = new ReentrantLock();
    //first-in-first-out (FIFO) wait queues.先进先出队列
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    final LinkedList<T> lists = new LinkedList<>();
    final int MAX_COUNT = 10;
    private int count = 0;

    /**
     * 加锁,防止count与实际lists大小不一致
     *
     * @param t
     */
    public void put(T t) {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " put start...");
            /**
             * 这里为什么不能用if,因为当前线程在等待时,其他线程也有机会执行put使得list.size发生改变,所以需要继续执行 == MAX_COUNT的判断
             */
            while (lists.size() == MAX_COUNT) {
                try {
                    System.out.println(Thread.currentThread().getName() + " waiting...");
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lists.add(t);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            count++;
            //可以选择只唤醒消费者
            consumer.signalAll();
            System.out.println(Thread.currentThread().getName() + " put end...");
        } finally {
            lock.unlock();
        }
    }

    public synchronized T get() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " get start...");
            T t = null;
            while (lists.size() == 0) {
                try {
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            t = lists.removeFirst();
            count--;
            producer.signalAll();
            System.out.println(Thread.currentThread().getName() + " get end...");
            return t;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLock4 reentrantLock4 = new ReentrantLock4();
        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(() -> {
                reentrantLock4.put("str");
            }, "put thread" + i);
            t.start();
        }

        for (int i = 0; i < 20; i++) {
            Thread t = new Thread(() -> {
                reentrantLock4.get();
            }, "get thread" + i);
            t.start();
        }
    }
}
put thread0 put start...
put thread0 put end...
put thread2 put start...
put thread2 put end...
put thread3 put start...
put thread3 put end...
put thread6 put start...
put thread6 put end...
put thread7 put start...
put thread7 put end...
put thread10 put start...
put thread10 put end...
put thread11 put start...
put thread11 put end...
get thread7 get start...
get thread7 get end...
put thread4 put start...
put thread4 put end...
put thread5 put start...
put thread5 put end...
put thread9 put start...
put thread9 put end...
put thread8 put start...
put thread8 put end...
put thread12 put start...
put thread12 waiting...
put thread13 put start...
put thread13 waiting...
put thread16 put start...
put thread16 waiting...
put thread17 put start...
put thread17 waiting...
put thread14 put start...
put thread14 waiting...
put thread15 put start...
put thread15 waiting...
put thread19 put start...
put thread19 waiting...
put thread18 put start...
put thread18 waiting...
put thread1 put start...
put thread1 waiting...
get thread17 get start...
get thread17 get end...
get thread16 get start...
get thread16 get end...
put thread12 put end...
put thread13 put end...
put thread16 waiting...
put thread17 waiting...
put thread14 waiting...
put thread15 waiting...
put thread19 waiting...
put thread18 waiting...
put thread1 waiting...
get thread18 get start...
get thread18 get end...
put thread16 put end...
put thread17 waiting...
put thread14 waiting...
put thread15 waiting...
put thread19 waiting...
put thread18 waiting...
put thread1 waiting...
get thread15 get start...
get thread15 get end...
put thread17 put end...
put thread14 waiting...
put thread15 waiting...
put thread19 waiting...
put thread18 waiting...
put thread1 waiting...
get thread19 get start...
get thread19 get end...
put thread14 put end...
put thread15 waiting...
put thread19 waiting...
put thread18 waiting...
put thread1 waiting...
get thread14 get start...
get thread14 get end...
put thread15 put end...
put thread19 waiting...
put thread18 waiting...
put thread1 waiting...
get thread11 get start...
get thread11 get end...
put thread19 put end...
put thread18 waiting...
put thread1 waiting...
get thread10 get start...
get thread10 get end...
put thread18 put end...
put thread1 waiting...
get thread6 get start...
get thread6 get end...
get thread3 get start...
get thread3 get end...
put thread1 put end...
get thread2 get start...
get thread2 get end...
get thread13 get start...
get thread13 get end...
get thread12 get start...
get thread12 get end...
get thread9 get start...
get thread9 get end...
get thread8 get start...
get thread8 get end...
get thread5 get start...
get thread5 get end...
get thread4 get start...
get thread4 get end...
get thread1 get start...
get thread1 get end...
get thread0 get start...
get thread0 get end...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值