并发编程总结

一.ReentrantLock总结

1.一些方法:
ReentrantLock reentrantLock = new ReentrantLock();
1)加锁
reentrantLock.lock();
2)释放锁
reentrantLock.unlock();
3)尝试获取锁 获取不到返回false,获取不到直接放弃,不进入阻塞队列
reentrantLock.tryLock();
4)在给定时间内获取锁,获取不到就退出
reentrantLock.tryLock(2, TimeUnit.SECONDS);
5)锁绑定多个条件:一个 ReentrantLock 可以同时绑定多个 Condition 对象,更细粒度的唤醒线程,
通过reentrantLock.newCondition()创建一个条件变量condition
通过condition.await()方法,当前线程进入condition等待,释放锁;
通过condition.singal()方法,唤醒在condition中的线程;
6)reentrantLock.lockInterruptibly()`:获得可打断的锁


public static void main(String[] args) throws InterruptedException {    
    ReentrantLock lock = new ReentrantLock();    
    Thread t1 = new Thread(() -> {        
        try {            
            System.out.println("尝试获取锁");            
            lock.lockInterruptibly();        
        } catch (InterruptedException e) {            
            System.out.println("没有获取到锁,被打断,直接返回");            
            return;        
        }        
        try {            
            System.out.println("获取到锁");        
        } finally {            
            lock.unlock();        
        }    
    }, "t1");    
    lock.lock();    
    t1.start();    
    Thread.sleep(2000);    
    System.out.println("主线程进行打断锁");    
    t1.interrupt();
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容