java Lock接口

在 Java 中,Lock 接口的实现类ReentrantLock 类提供了比使用 synchronized 方法和代码块更广泛的锁定机制。

简单示例:

java 复制代码
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockExample {
    private final Lock lock = new ReentrantLock();
    private int counter = 0;

    public void increment() {
        lock.lock();
        try {
            counter++;
        } finally {
            lock.unlock();
        }
    }

    public int getCounter() {
        lock.lock();
        try {
            return counter;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockExample example = new ReentrantLockExample();
        example.increment();
        System.out.println("Counter: " + example.getCounter());
    }
}

生产者-消费者示例:

java 复制代码
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer {

    private final Queue<Integer> queue = new LinkedList<>();
    private final int CAPACITY = 5;
    private final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    public void produce() throws InterruptedException {
        int value = 0;
        while (true) {
            lock.lock();
            try {
                while (queue.size() == CAPACITY) {
                    notFull.await();
                }
                queue.add(value);
                System.out.println("Produced " + value);
                value++;
                notEmpty.signal();
            } finally {
                lock.unlock();
            }
            Thread.sleep(1000); // Simulate time taken to produce an item
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            lock.lock();
            try {
                while (queue.isEmpty()) {
                    notEmpty.await();
                }
                int value = queue.poll();
                System.out.println("Consumed " + value);
                notFull.signal();
            } finally {
                lock.unlock();
            }
            Thread.sleep(1500); // Simulate time taken to consume an item
        }
    }

    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread producerThread = new Thread(() -> {
            try {
                pc.produce();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumerThread = new Thread(() -> {
            try {
                pc.consume();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}
相关推荐
潘多编程4 分钟前
Java中的状态机实现:使用Spring State Machine管理复杂状态流转
java·开发语言·spring
_阿伟_23 分钟前
SpringMVC
java·spring
代码在改了30 分钟前
springboot厨房达人美食分享平台(源码+文档+调试+答疑)
java·spring boot
冷静 包容42 分钟前
C语言学习之 没有重复项数字的全排列
c语言·开发语言·学习
碳苯1 小时前
【rCore OS 开源操作系统】Rust 枚举与模式匹配
开发语言·人工智能·后端·rust·操作系统·os
wclass-zhengge1 小时前
数据结构篇(绪论)
java·数据结构·算法
何事驚慌1 小时前
2024/10/5 数据结构打卡
java·数据结构·算法
结衣结衣.1 小时前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
学习使我变快乐1 小时前
C++:静态成员
开发语言·c++
TJKFYY1 小时前
Java.数据结构.HashSet
java·开发语言·数据结构