1.前言 ReentrantLock可以有公平锁和非公平锁的不同实现,只要在构造它的时候传入不同的布尔值,继续跟进下源码我们就能发现,关键在于实例化内部变量sync的方式不同,如下所示: /** * Creates an instance of {@code ReentrantLock} with the * given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering po
//效果和synchronized一样,都可以同步执行,lock方法获得锁,unlock方法释放锁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()
一.简介 JDK提供了Lock接口来实现更丰富的锁控制,ReentrantLock即Lock接口的实现 JDK文档:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/locks/ReentrantLock.html 二.代码示例 import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockDemo { private st
(一)Java中线程协作的最常见的两种方式: (1)利用Object的wait().notify()和notifyAll()方法及synchronized (2)使用Condition.ReentrantLock (二)Object类的wait().notify()和notifyAll()方法 /** * Wakes up a single thread that is waiting on this object's * monitor. If any threads are waiting