使用synchronized 实现ReentrantLock(美团面试题目)

    刚看到这个题目的时候无从下手,因为觉得synchronized和lock在加锁的方式上有很大不同,比如,看看正常情况下synchronized时如何加锁的。

        方式一: 

public synchronized void a(){  
    //TODO  
}  

        方式二: 

public void b(){  
    synchronized(this){  
        //TODO  
    }  
} 

 

        从这两种方式来看,锁都是加在{}之间的,我们再来看看Lock是如何做的呢: 

public void c() {  
    lock.lock();  
    try {  
        // TODO  
    } finally {  
        lock.unlock();  
    }  
}  

         这种方式的锁是加在lock() 和unlock()之间的,所以要想实现一个lock功能,就要想怎么实现这样两个方法,lock()和unlock()方法,先定义一个框架如下所示: 

public void lock(){        
}    
public void unlock(){        
}   

        然后要想怎么用synchronized去实现这两个方法。 

        现在其实只是稍微清楚了一点思路,但是还不知道怎么去填充这两个方法,这是后再来分析一下Lock的加锁有什么特点,再来看看这段代码:

复制代码
public void c() {  
    lock.lock();//When current thread get the lock, other thread has to wait  
    try {  
        //current thread get in the lock, other thread can not get in  
        // TODO  
    } finally {  
        lock.unlock();//current thread release the lock  
    }  
}  
复制代码

         这段代码我只是加了一点注释,别的什么都没有做,是不是帮助理解这段代码,看看出现频率最高的词是什么,是current thread,那么我们去填充lock()和unlock()方法的时候是不是注意要抓住current thread这个关键字就可以找到解决方案呢?答案是肯定的。 

        接着分析,使用synchronized的时候如何让线程等待呢?是用wait()方法。怎么让线程唤醒呢,是用notify()方法。那么就要在lock()方法中使用wait()方法,在unlock()方法中使用notify()方法。那么我们在使用wait()和notify()的时候是有一个条件的,想想我们应该使用什么作为条件呢?

        我们应该使用当前锁是否被占用作为判断条件,如果锁被占用,current thread等待,想想我们在使用synchronized的时候是不是一直使用的这个条件,答案也是肯定的。

        再来分析一下什么时候释放锁,使用什么作为条件,想想如果线程A拿到了锁,线程B能释放吗?当然不能,如果B能释放就违反了原则,当然不能。肯定是A线程的锁只能A来释放。所以判断条件就是判断持有锁的线程是不是current thread,如果是的话,可以释放,不是的话当然不能。

        现在来看看完整的代码:网上写的有点乱,我自己从新整理了一下,并且可以正常运行  

复制代码
package test_lock;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class NaiveLock {
    
    private static final long NONE=-1;
    private long owner =NONE;
    
    public synchronized void lock(){
        long currentThreadId=Thread.currentThread().getId();
        if(owner==currentThreadId){
            throw new IllegalStateException("lock has been acquired by current thread");
        }
        
        while(this.owner!=NONE){
            
            System.out.println(String.format("thread %s is waiting lock", currentThreadId));
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.owner=currentThreadId;
        System.out.println(String.format("lock is acquired by thread %s", currentThreadId));
        
    }
    
    public synchronized void unlock(){
        
        long currentThreadId=Thread.currentThread().getId();
        
        if(this.owner!=currentThreadId){
            throw new IllegalStateException("Only lock owner can unlock the lock");
        }
        
        System.out.println(String.format("thread %s is unlocking", owner));
        owner=NONE;
        notify();
        
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final NaiveLock lock=new NaiveLock();
        ExecutorService executor= Executors.newFixedThreadPool(20, new ThreadFactory(){
             private ThreadGroup group =new ThreadGroup("test thread group");
             {
             group.setDaemon(true);
             }
            @Override
            public Thread newThread(Runnable r) {
                // TODO Auto-generated method stub
                return new Thread(group,r);
            }});
        
        
        for(int i=0;i<20;i++){
            executor.submit(new Runnable(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    lock.lock();
                    System.out.println(String.format("thread %s is running...", Thread.currentThread().getId()));
                    
                    
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    lock.unlock();
                }});
        }
        

    }

}
复制代码

结果为:

复制代码
lock is acquired by thread 10
thread 10 is running...
thread 29 is waiting lock
....
thread 13 is running... thread 13 is unlocking lock is acquired by thread 12 thread 12 is running... thread 12 is unlocking
复制代码

 

posted @   aspirant  阅读(5647)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示