解析:lock接口在多线程和并发编程中最大的优势是它们为读和写分别提供了锁,它能满足你写像 ConcurrentHashMap 这样的高性能数据结构和有条件的阻塞。Java线程面试的问题越来越会根据面试者的回答来提问。我强烈建议在你去参加多线程的面试之前认真读一下Locks,因为当前其大量用于构建电子交易终统的客户端缓存和交易连接空间。Lock读写锁机制可以实现! 在Java中Lock接口比synchronized块的优势是什么?
Lock接口最大的优势是为读和写分别提供了锁。
packagetech.luxsun.interview.luxinterviewstarter.thread; importjava.time.LocalDateTime; importjava.util.concurrent.ThreadLocalRandom; importjava.util.concurrent.locks.ReadWriteLock; importjava.util.concurrent.locks.ReentrantReadWriteLock; /*** @author Lux Sun* @date 2021/4/11*/publicclassLockDemo { publicstaticvoidmain(String[] args) { // 初始化Cachecache=newCache(); // 读取for (inti=0; i<5; i++) { newThread(() ->cache.get()).start(); } // 写入for (inti=0; i<5; i++) { newThread(() ->cache.put(ThreadLocalRandom.current().nextInt(1000))).start(); } } } classCache { privateIntegerdata=0; privateReadWriteLockrwLock=newReentrantReadWriteLock(); publicvoidget() { // try...catch...finally 防止死锁try { // 读锁开启, 读进程均可进入rwLock.readLock().lock(); System.out.println(Thread.currentThread().getName() +"read lock is ready..."+LocalDateTime.now()); Thread.sleep(1000); System.out.println(Thread.currentThread().getName() +"read data is "+data); } catch (InterruptedExceptione) { e.printStackTrace(); } finally { // 读锁解锁rwLock.readLock().unlock(); } } publicvoidput(Integerdata) { try { // 写锁开启, 写进程只允许进一个rwLock.writeLock().lock(); System.out.println(Thread.currentThread().getName() +"write lock is ready..."+LocalDateTime.now()); Thread.sleep(1000); this.data=data; System.out.println(Thread.currentThread().getName() +"write data is "+data); } catch (InterruptedExceptione) { e.printStackTrace(); } finally { // 写锁解锁rwLock.writeLock().unlock(); } } }
Thread-4readlockisready...2021-04-11T17:44:57.733Thread-0readlockisready...2021-04-11T17:44:57.733Thread-3readlockisready...2021-04-11T17:44:57.733Thread-1readlockisready...2021-04-11T17:44:57.733Thread-2readlockisready...2021-04-11T17:44:57.733Thread-0readdatais0Thread-3readdatais0Thread-2readdatais0Thread-1readdatais0Thread-4readdatais0Thread-8writelockisready...2021-04-11T17:44:58.735Thread-8writedatais118Thread-9writelockisready...2021-04-11T17:44:59.735Thread-9writedatais560Thread-5writelockisready...2021-04-11T17:45:00.736Thread-5writedatais333Thread-7writelockisready...2021-04-11T17:45:01.737Thread-7writedatais685Thread-6writelockisready...2021-04-11T17:45:02.737Thread-6writedatais507