说起来用起来其实很简单 ReentrantLock
公平锁的就是我先到了,发出申请,此时我一定排在那到锁队列的前面
非公平锁,就是 我要拿锁 有人拿了,我排队,没人拿,就是我的 排队的等着
package Concurrency.mid; import java.util.concurrent.locks.ReentrantLock; class Service{ private ReentrantLock lock; public Service(boolean flag){ lock = new ReentrantLock(flag); } public void serviceMethod(){ try{ lock.lock(); System.out.println(Thread.currentThread().getName()+ "锁定成功"); }finally { lock.unlock(); } } } public class ReentrantLockTest { public static void main(String []arg){ final Service s= new Service(true); Runnable r = new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+ "运行了 成功"); s.serviceMethod(); } }; Thread [] t = new Thread[10]; for(int i=0;i<10;i++){ t[i] = new Thread(r); } for(int i=0;i<10;i++){ t[i].start(); } } }
实现源码 看不懂(等我在学学的 再补)