java中多线程加锁的四种方式
在Java中,多线程加锁的方式主要有以下几种:
1. 使用synchronized关键字
synchronized可以用于方法或代码块,确保只有一个线程能访问被锁定的代码。
方法锁
class SynchronizedMethod {
public synchronized void synchronizedMethod() {
System.out.println("Synchronized method executed by " + Thread.currentThread().getName());
}
}
代码块锁
class SynchronizedBlock {
private final Object lock = new Object();
public void synchronizedBlock() {
synchronized (lock) {
System.out.println("Synchronized block executed by " + Thread.currentThread().getName());
}
}
}
2. 使用ReentrantLock类
ReentrantLock是java.util.concurrent.locks包中的一种锁,具有比synchronized更灵活的锁定机制。
import java.util.concurrent.locks.ReentrantLock;
class ReentrantLockExample {
private final ReentrantLock lock = new ReentrantLock();
public void lockMethod() {
lock.lock();
try {
System.out.println("ReentrantLock method executed by " + Thread.currentThread().getName());
} finally {
lock.unlock();
}
}
}
3. 使用读写锁(ReadWriteLock)
ReadWriteLock允许多个读线程同时访问共享资源,但在写线程访问时,阻止其他线程的读和写访问。
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class ReadWriteLockExample {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void readMethod() {
readWriteLock.readLock().lock();
try {
System.out.println("Read lock method executed by " + Thread.currentThread().getName());
} finally {
readWriteLock.readLock().unlock();
}
}
public void writeMethod() {
readWriteLock.writeLock().lock();
try {
System.out.println("Write lock method executed by " + Thread.currentThread().getName());
} finally {
readWriteLock.writeLock().unlock();
}
}
}
4. 使用信号量(Semaphore)
Semaphore是一种计数信号量,可以限制同时访问某个资源的线程数量。
import java.util.concurrent.Semaphore;
class SemaphoreExample {
private final Semaphore semaphore = new Semaphore(2); // 允许最多两个线程访问
public void accessResource() {
try {
semaphore.acquire();
System.out.println("Accessing resource by " + Thread.currentThread().getName());
Thread.sleep(1000); // 模拟工作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
总结
synchronized是 Java 内置的关键字,易于使用,但灵活性不足。ReentrantLock提供了更强大的锁控制能力,如可重入锁、超时锁。ReadWriteLock允许更高效地处理读写操作,适用于读多写少的场景。Semaphore可以控制访问资源的线程数量,适合有限资源的场景。
这些加锁机制可以帮助你在多线程环境中实现线程安全的访问
到此这篇关于java中多线程加锁的四种方式的文章就介绍到这了,更多相关java 多线程加锁内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringSecurity HttpSecurity 类处理流程分析
SpringSecurity在SSM项目中使用基于配置文件,通过XML标签定义认证信息,HttpSecurity在SpringBoot中通过代码配置实现与XML相同功能,详细介绍了HttpSecurity的类结构、处理过程及其与SecurityBuilder的关系,感兴趣的朋友一起看看吧2024-09-09
mybatis plus框架@TableField注解不生效问题及解决方案
最近遇到一个mybatis plus的问题,@TableField注解不生效,导致查出来的字段反序列化后为空,今天通过本文给大家介绍下mybatis plus框架的@TableField注解不生效问题总结,需要的朋友可以参考下2022-03-03
spring boot 加载web容器tomcat流程源码分析
本文章主要描述spring boot加载web容器 tomcat的部分,为了避免文章知识点过于分散,其他相关的如bean的加载,tomcat内部流程等不做深入讨论,具体内容详情跟随小编一起看看吧2021-06-06


最新评论