用java实现一个行锁(RowLock)

java 版本的数据库行锁,使用wait/notify实现,当然可以使用别的方式如Lock下的await/signal

需求使用java写一个类,这个类有一个lock(String identifier)方法,用于传入一个唯一的标识标识数据库的某一行或者某个集合的某一条记录,当上锁之后,如果不适用unLock(String identifier)方法解锁,那么用于就不能访问这一条数据

 

直接上代码:

package com.lyzx.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class JavaRowLock{
    private ConcurrentHashMap<String,Object> lockedMap = new ConcurrentHashMap();

    public synchronized void lock(String id) throws InterruptedException{
        while(lockedMap.containsKey(id)){
            wait();
        }
        lockedMap.put(id,"");
    }

    public synchronized void unLock(String id){
        if(lockedMap.containsKey(id)){
            lockedMap.remove(id);
            notifyAll();
        }
    }

    public static void main(String[] args){
        JavaRowLock lock = new JavaRowLock();

        List<Runnable> arr = new ArrayList<>();

        for(int i = 0;i<100;i++){
            arr.add(new A1(lock,"A"));
        }

        for(int i=0;i<arr.size();i++){
            new Thread(arr.get(i),"A"+(i+1)).start();
        }
        try{Thread.sleep(1000);}catch(InterruptedException e){e.printStackTrace();}
    }
}

class A1 implements Runnable{
    private JavaRowLock lock;
    private String id;
    
    public A1(JavaRowLock lock,String id){
        this.lock = lock;
        this.id = id;
    }

    @Override
    public void run(){
        String threadName = Thread.currentThread().getName();
        try{
            lock.lock(id);
            System.out.println("线程:"+threadName+" 为["+id+"]加锁");
            System.out.println("线程:"+threadName+" 执行业务代码");
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unLock(id);
            System.out.println("线程:"+threadName+" 释放锁");
        }
    }
}

 

    原文作者:java锁
    原文地址: https://blog.csdn.net/lyzx_in_csdn/article/details/82722133
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞