Java 的行级锁实现

本文探讨了在Java中实现行锁的思路,强调其在高并发场景下的应用。通过提供一个使用`ConcurrentHashMap`作为基础的行锁设计示例,作者鼓励读者进行讨论和指正。

用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();
    }

}

}

以上是 代码实现 和 测试类。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值