Java多線程和並發(九),ReentrantLock(公平鎖)
阿新 • • 發佈:2019-02-11
code rtl cat read thread ron true sta 目錄 3.synchronized和ReentrantLock
目錄
1.ReentrantLock
2.ReentrantLock的實現
3.synchronized和ReentrantLock的區別
九、ReentrantLock(公平鎖)
1.ReentrantLock
2.ReentrantLock的實現
public class ReentrantLockDemo implements Runnable{ private static ReentrantLock lock = new ReentrantLock(true); @Override public void run(){ while (true){ try{ lock.lock(); System.out.println(Thread.currentThread().getName() + " get lock"); Thread.sleep(1000); } catch (Exception e){ e.printStackTrace(); } finally { lock.unlock(); } } }public static void main(String[] args) { ReentrantLockDemo rtld = new ReentrantLockDemo(); Thread thread1 = new Thread(rtld); Thread thread2 = new Thread(rtld); thread1.start(); thread2.start(); } }
只有當ReentrantLock構造中傳入為true時才是公平鎖
3.synchronized和ReentrantLock 的區別
Java多線程和並發(九),ReentrantLock(公平鎖)