多线程(4)
显示锁
1定义:显示声明的锁,比如reentrantlock
非显示锁sychronized
公平锁,非公平锁
1定义:这个是reentrantlock底层,默认为非公平锁,速度快
读写锁
1:reentrantlock的分为读写锁,口诀:读读共享,写写互斥,读写互斥
2:应用场景:多读写少的场景
阻塞与唤醒 Condition
1:对于同一个lock,可以加上Condition进行等待唤醒控制
2:比如生产者消费者问题:
package cn.enjoyedu.ch4.rw;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
public class Test1 {
private static Lock lock = new ReentrantLock();
private static Condition notEmpty = lock.newCondition();
private static Condition notFull = lock.newCondition();
private static volatile int count = 0;
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(6);
pool.execute(new Gun(lock, notEmpty, notFull));
pool.execute(new Bullet(lock, notEmpty, notFull));
}
public static class Gun implements Runnable {
private Lock lock;
private Condition notEmpty;
private Condition notFull;
public Gun(Lock lock, Condition notEmpty, Condition notFull) {
this.lock = lock;
this.notEmpty = notEmpty;
this.notFull = notFull;
}
public void run() {
while (true) {
lock.lock();
while (count == 0) {
try {
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("射击---biubiubiu");
count--;
notFull.signal();
lock.unlock();
}
}
}
public static class Bullet implements Runnable {
private Lock lock;
private Condition notEmpty;
private Condition notFull;
public Bullet(Lock lock, Condition notEmpty, Condition notFull) {
this.lock = lock;
this.notEmpty = notEmpty;
this.notFull = notFull;
}
public void run() {
while (true) {
lock.lock();
while (count >= 20) {
try {
notFull.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("压入子弹---铛铛");
count++;
notEmpty.signal();
lock.unlock();
}
}
}
}
不恋尘世浮华,不写红尘纷扰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理