用Java 实现行锁(区别于表锁)
大家好,前几天跟一位朋友交流技术,说到了Java中的锁机制,其实锁机制在现在的大用户量,高并发场景下的使用很常见,但是如果说让自己来实现一个行级锁,这种细粒度的实现,确实是需要仔细思考的,下面的代码是我写的一个设计思路,欢迎大家批评指正。
import java.util.concurrent.ConcurrentHashMap;
public class MyRowLock {
private ConcurrentHashMap map = new ConcurrentHashMap();
/**
* 行锁的加锁方法
*/
public synchronized void lock(String id) throws Exception{
//System.out.println("当前线程 " + Thread.currentThread().getName());
while(map.containsKey(id)){
wait();
}
map.put(id,"");
//System.out.println("线程 " + Thread.currentThread().getName() + "拿到锁 , 锁定资源" + id);
}
/**
* 行锁的解锁方法
*/
public synchronized void unlock(String id){
while(map.containsKey(id)){
map.remove(id);
//System.out.println("线程 " + Thread.currentThread().getName() + "释放锁 , 释放资源" + id);
notifyAll();
}
}
}
class MyThread implements Runnable{
private MyRowLock myRowLock;
private String id;
public MyThread(MyRowLock myRowLock , String id) {
this.myRowLock = myRowLock;
this.id = id;
}
@Override
public void run() {
try{
//System.out.println("当前线程 " + Thread.currentThread().getName());
myRowLock.lock(id);
System.out.println("线程 " + Thread.currentThread().getName() + "拿到锁 , 锁定资源" + id);
System.out.println("******执行业务逻辑******");
}catch(Exception e){
}finally {
System.out.println("线程 " + Thread.currentThread().getName() + "释放锁 , 释放资源" + id);
myRowLock.unlock(id);
}
}
}
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
MyRowLock myRowLock = new MyRowLock();
ArrayList<MyThread> list = new ArrayList();
ArrayList<MyThread> list1 = new ArrayList();
for (int i = 0; i < 100; i++) {
list.add(new MyThread(myRowLock,"A"));
}
for (int i = 0; i < 100; i++) {
list1.add(new MyThread(myRowLock,"B"));
}
for (int i = 0; i < 100; i++) {
new Thread(list.get(i),i+"A").start();
new Thread(list1.get(i),i+"B").start();
}
}
}
以上是 代码实现 和 测试类。
本文探讨了在Java中实现行锁的思路,强调其在高并发场景下的应用。通过提供一个使用`ConcurrentHashMap`作为基础的行锁设计示例,作者鼓励读者进行讨论和指正。
393

被折叠的 条评论
为什么被折叠?



