ReentrantLock——公平鎖與非公平鎖對比
阿新 • • 發佈:2018-11-04
/** * 公平鎖非公平鎖 */ @Test public void FairLockAndNotFairLockTest() throws Exception { ReentrantLock2 fairLock = new ReentrantLock2(true); ReentrantLock2 unFairLock = new ReentrantLock2(false); testLock("公平鎖",fairLock); testLock("非公平鎖", unFairLock); } class Job extends Thread { private Lock lock; Job(Lock lock) { this.lock = lock; } @Override public void run() { for (int i = 0; i < 2; i++) { lock.lock(); try { Thread.sleep(1000); System.out.println("current thread name : " + Thread.currentThread().getName() + " ; 同步佇列中的執行緒 :" + ((ReentrantLock2) lock).getQueuedThreads()); } catch (Exception e) { System.out.println(e); } finally { lock.unlock(); } } } } private void testLock(String type, Lock lock) throws InterruptedException { System.out.println(type); for (int i = 0; i < 5; i++) { Thread thread = new Thread(new Job(lock)) { public String toString() { return getName(); } }; thread.setName("" + i); thread.start(); } Thread.sleep(11000); } public class ReentrantLock2 extends ReentrantLock { ReentrantLock2(boolean fair) { super(fair); } /** * 獲取等待鎖執行緒列表 * * @return */ public Collection<Thread> getQueuedThreads() { List<Thread> threads = new ArrayList<>(super.getQueuedThreads()); Collections.reverse(threads); return threads; } }
總結:
- 總體來說,公平鎖需要更多的執行緒切換,整體上效能不如非公平鎖好。