java 锁的应用代码案例
Java中的锁是一种用于控制多线程访问共享资源的机制。锁的使用可以保证在同一时刻只有一个线程可以访问共享资源,从而避免了多线程并发访问可能引发的数据不一致或冲突的问题。下面是10个使用Java锁的应用代码案例。
1. 使用ReentrantLock实现线程安全的计数器
```java
import urrent.locks.ReentrantLock;
public class Counter {
private int count = 0;
private ReentrantLock lock = new ReentrantLock();
public void increment() {
java单例模式双重锁
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
```
2. 使用synchronized关键字实现线程安全的单例模式
```java
public class Singleton {
private static Singleton instance;
private static Object lock = new Object();
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (lock) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
```
3. 使用ReadWriteLock实现读写分离的缓存
```java
import java.util.HashMap;
import java.util.Map;
import urrent.locks.ReadWriteLock;
import urrent.locks.ReentrantReadWriteLock;
public class Cache {
private Map<String, Object> cacheMap = new HashMap<>();
private ReadWriteLock lock = new ReentrantReadWriteLock();
public Object get(String key) {
adLock().lock();
try {
(key);
} finally {
adLock().unlock();
}
}
public void put(String key, Object value) {
lock.writeLock().lock();
try {
cacheMap.put(key, value);
} finally {
lock.writeLock().unlock();
}
}
}
```
4. 使用Condition实现生产者-消费者模式
```java
import java.util.LinkedList;
import java.util.Queue;
import urrent.locks.Condition;
import urrent.locks.Lock;
import urrent.locks.ReentrantLock;
public class ProducerConsumer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity = 10;
private Lock lock = new ReentrantLock();
private Condition notFull = wCondition();
private Condition notEmpty = wCondition();
public void produce(int num) throws InterruptedException {
lock.lock();
try {
while (queue.size() == capacity) {
notFull.await();
}
queue.offer(num);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论