ReentrantLock的使用
发布时间:2020-12-15 05:35:03 所属栏目:Java 来源:网络整理
导读:ReentrantLocak特性(对比synchronized) 尝试获得锁 获取到锁的线程能够响应中断 ReentrantLock(重入锁) public class MyService { private Lock lock = new ReentrantLock(); public void testMethod( ) { lock. lock(); for ( int i = 0; i 5; i++) { Sys
ReentrantLocak特性(对比synchronized)
ReentrantLock(重入锁)public class MyService { private Lock lock = new ReentrantLock(); public void testMethod() { lock.lock(); for (int i = 0; i < 5; i++) { System.out.println("ThreadName=" + Thread.currentThread().getName() + (" " + (i + 1))); } lock.unlock(); } }
效果和synchronized一样,都可以同步执行,lock方法获得锁,unlock方法释放锁 await方法public class MyService { private Lock lock = new ReentrantLock(); private Condition condition=lock.newCondition(); public void testMethod() { try { lock.lock(); System.out.println("开始wait"); condition.await(); for (int i = 0; i < 5; i++) { System.out.println("ThreadName=" + Thread.currentThread().getName() + (" " + (i + 1))); } } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { lock.unlock(); } } }
signal方法public void signal() { try { lock.lock(); condition.signal(); } finally { lock.unlock(); } }
创建多个condition对象
Condition类和Object类
Lock的公平锁和非公平锁Lock lock=new ReentrantLock(true);//公平锁 Lock lock=new ReentrantLock(false);//非公平锁
ReentrantLock类的方法
tryLock和lock和lockInterruptibly的区别
读写锁
public void read() { try { try { lock.readLock().lock(); System.out.println("获得读锁" + Thread.currentThread().getName() + " " + System.currentTimeMillis()); Thread.sleep(10000); } finally { lock.readLock().unlock(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void write() { try { try { lock.writeLock().lock(); System.out.println("获得写锁" + Thread.currentThread().getName() + " " + System.currentTimeMillis()); Thread.sleep(10000); } finally { lock.writeLock().unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } }
public void read() { try { try { lock.readLock().lock(); System.out.println("获得读锁" + Thread.currentThread().getName() + " " + System.currentTimeMillis()); Thread.sleep(10000); } finally { lock.readLock().unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } } public void write() { try { try { lock.writeLock().lock(); System.out.println("获得写锁" + Thread.currentThread().getName() + " " + System.currentTimeMillis()); Thread.sleep(10000); } finally { lock.writeLock().unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } }
总结
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |