线程: ReentrantLock类
生活随笔
收集整理的這篇文章主要介紹了
线程: ReentrantLock类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用ReentrantLock實現(xiàn)同步
? ReentrantLock對象的lock()方法獲取鎖, 調(diào)用unlock()方法釋放鎖
? 調(diào)用ReentrantLock對象的lock()方法的線程就持有"對象監(jiān)視器",其他線程只有等待鎖被釋放時再次爭搶。效果和使用synchronized關鍵字一樣。
? ?關鍵字synchronized與wait()和notify()/notifyAll()方法相結(jié)合可以實現(xiàn)等待/通知模式, 類ReentrantLock也可以實現(xiàn)同樣的功能,但需要借助于Condition對象。Condition類是再jdk5中出現(xiàn)的技術,使用它有更好的靈活性,比如可以實現(xiàn)多路通知功能。使用ReentrantLock結(jié)合Condition類是可以實現(xiàn)"選擇性通知",這個功能非常重要。
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;public class MySservice {private ReentrantLock lock = new ReentrantLock();private Condition conditionA = lock.newCondition();private Condition conditionB = lock.newCondition();private boolean hasValue = false;public void set(){try {lock.lock();while(hasValue == true){System.out.println("setsetsetset"+Thread.currentThread().getName());conditionA.await();}System.out.println("set");hasValue = true;conditionB.signal();} catch (InterruptedException e) {e.printStackTrace();}finally {lock.unlock();}}public void get(){try {lock.lock();while(hasValue == false){System.out.println("getgetgetget");conditionB.await();}System.out.println("get");hasValue = false;conditionA.signal();} catch (InterruptedException e) {e.printStackTrace();}finally {lock.unlock();}} }public class MyThreadA extends Thread {private MySservice mySservice;public MyThreadA(MySservice mySservice){super();this.mySservice = mySservice;}@Overridepublic void run(){for (int i = 0; i < Integer.MAX_VALUE; i++) {mySservice.set();}} }public class MyThreadB extends Thread {private MySservice mySservice;public MyThreadB(MySservice mySservice){super();this.mySservice = mySservice;}@Overridepublic void run(){for (int i = 0; i < Integer.MAX_VALUE; i++) {mySservice.get();}} }public class Run {public static void main(String[] args) {MySservice mySservice = new MySservice();MyThreadA[] myThreadA = new MyThreadA[10];MyThreadB[] myThreadB = new MyThreadB[10];for (int i = 0; i < 10; i++) {myThreadA[i] = new MyThreadA(mySservice);myThreadB[i] = new MyThreadB(mySservice);myThreadA[i].setName((i+1)+"");myThreadA[i].start();myThreadB[i].start();}} }方法getHoldCount()
? 該方法是查詢當前線程保持此鎖定的個數(shù),也就是調(diào)用lock()方法的次數(shù)
import java.util.concurrent.locks.ReentrantLock;public class Service {private ReentrantLock lock = new ReentrantLock();public void serviceMethod1(){try{lock.lock();System.out.println("serviceMethod1 getHoldCount="+lock.getHoldCount());serviceMethod2();}finally {lock.unlock();}}public void serviceMethod2(){try{lock.lock();System.out.println("serviceMethod2 getHoldCount="+lock.getHoldCount());}finally {lock.unlock();}} }public class Run {public static void main(String[] args) {Service service = new Service();service.serviceMethod1();} }?方法getQueueLength()
??返回正等待獲取此鎖定的線程估計數(shù)。
public class Run {public static void main(String[] args) throws InterruptedException {final Service service = new Service();Runnable runnable = new Runnable() {@Overridepublic void run() {service.serviceMethod1();}};Thread[] threadArray = new Thread[10];for (int i = 0; i < 10; i++) {threadArray[i] = new Thread(runnable);}for (int i = 0; i < 10; i++) {threadArray[i].start();}Thread.sleep(2000);System.out.println("有線程樹:"+service.lock.getQueueLength()+"正在等待鎖!");} }import java.util.concurrent.locks.ReentrantLock;public class Service {public ReentrantLock lock = new ReentrantLock();public void serviceMethod1(){try{lock.lock();System.out.println("ThreadName="+Thread.currentThread().getName()+" 進入方法!");Thread.sleep(1000);}catch(InterruptedException ex){ex.printStackTrace();}finally {lock.unlock();}} }方法hasQueuedThread(), hasQueuedThreads()
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;public class Service {public ReentrantLock lock = new ReentrantLock();public Condition newCondition = lock.newCondition();public void waitMethod(){try{lock.lock();Thread.sleep(Integer.MAX_VALUE);}catch (InterruptedException ex){ex.printStackTrace();}finally {lock.unlock();}} }public class Run {public static void main(String[] args) throws InterruptedException {final Service service = new Service();Runnable runnable = new Runnable() {@Overridepublic void run() {service.waitMethod();}};Thread threadA = new Thread(runnable);threadA.start();Thread.sleep(500);Thread threadB = new Thread(runnable);threadB.start();Thread.sleep(500);System.out.println(service.lock.hasQueuedThread(threadA));System.out.println(service.lock.hasQueuedThread(threadB));System.out.println(service.lock.hasQueuedThreads());System.out.println(service.lock.getQueueLength());} }方法isFair()
? ? ?判斷是不是公平鎖
import java.util.concurrent.locks.ReentrantLock;public class Service {private ReentrantLock lock;public Service(boolean isFair){super();lock = new ReentrantLock(isFair);}public void serviceMethod(){try{lock.lock();System.out.println(Thread.currentThread().getName()+" 公平鎖情況:"+lock.isFair());}finally {lock.unlock();}} }public class Run {public static void main(String[] args) {Service service1 = new Service(true);Runnable runnable = new Runnable() {@Overridepublic void run() {service1.serviceMethod();}};Thread t1 = new Thread(runnable,"A");t1.start();Service service2 = new Service(false);Runnable runnable2 = new Runnable() {@Overridepublic void run() {service2.serviceMethod();}};Thread t2 = new Thread(runnable2,"B");t2.start();} }方法isHeldByCurrentThread()
? 查詢當前線程是否保持此鎖定
import java.util.concurrent.locks.ReentrantLock;public class Service {private ReentrantLock lock;public Service(){super();lock = new ReentrantLock();}public void serviceMethod(){try{System.out.println("當前線程是否保持此鎖定"+lock.isHeldByCurrentThread());lock.lock();System.out.println("當前線程是否保持此鎖定"+lock.isHeldByCurrentThread());}finally {lock.unlock();}} }public class Run {public static void main(String[] args) {final Service service1 = new Service();Runnable runnable = new Runnable() {@Overridepublic void run() {service1.serviceMethod();}};Thread t = new Thread(runnable);t.start();} }方法tryLock(long timeout, TimeUnit unit)
? ? ?如果鎖定在給定等待時間內(nèi)沒有被另一個線程保持,且當前線程未被中斷,則獲取該鎖定
import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock;public class MyService {private ReentrantLock lock = new ReentrantLock();public void waitMethod(){try{if(lock.tryLock(3, TimeUnit.SECONDS)){System.out.println(" "+Thread.currentThread().getName()+"獲得鎖的時間:"+System.currentTimeMillis());Thread.sleep(10000);}else{System.out.println(" "+Thread.currentThread().getName()+"沒有獲得鎖");}}catch (InterruptedException ex){ex.printStackTrace();}finally {if(lock.isHeldByCurrentThread()){lock.unlock();}}} }public class Run {public static void main(String[] args) {final MyService service = new MyService();Runnable runnableRef = new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+" 調(diào)用waitMethod時間: "+System.currentTimeMillis());service.waitMethod();}};Thread threadA = new Thread(runnableRef);threadA.setName("A");threadA.start();Thread threadB = new Thread(runnableRef);threadB.setName("B");threadB.start();} }??
總結(jié)
以上是生活随笔為你收集整理的线程: ReentrantLock类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程:类ThreadLocal的使用
- 下一篇: 线程:ReentrantReadWrit