Java笔记-多线程协调及ReentrantLock的使用
這里使用wait/notify去協調線程。
感覺這個比C/C++里面信號量還要好用一點。
?
使用synchronized沒有解決多線程協調問題
public synchronized String getTask(){while(queue.isEmpty()){this.wait();}return queue.remove; }wait是在Object上的代碼,是jvm上的C代碼實現的,必須包含在synchronized中。
?
使用wait/notify線程協調機制
public synchronized void addTask(String s){this.queue.add(s);this.notify(); }public synchronized String getTask(){while(queue.isEmpty()){this.wait();}return queue.remove; }因為wait方法會釋放鎖,其他方法就可以得到鎖,這樣就可以協調工作了。
this.notify()喚醒正在wait()的方法。
如下程序運行截圖如下:
源碼如下:
下面是關于ReentrantLock
java.util.locks.ReentrantLock用于替代synchronized加鎖:
如下:
synchronized(lockObj){n = n + 1; }替代為:
lock.lock(); try{n = n + 1; } finally{lock.unlock(); }java.util.locks.ReentrantLock用于替代synchronized加鎖:
class Counter{final Lock lock = new ReentrantLock();public void inc(){lock.lock();try{n = n + 1;}finally{lock.unlock();}} }ReentrantLock:
可重入鎖,一個線程可多次獲取同一個鎖。
lock()方法可獲取鎖。
tryLock()方法可嘗試獲取鎖,并可指定超時。
?
關鍵就是這指定超時。
如下例子!
程序運行截圖如下:
源碼如下:
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;class Counter{private Lock lock = new ReentrantLock();private int value = 0;public void add(int m){lock.lock();try{this.value += m;}finally {lock.unlock();}}public void dec(int m){lock.lock();try{this.value -= m;}finally {lock.unlock();}}public int get(){lock.lock();try{return this.value;}finally {lock.unlock();}} }public class Main2 {final static int LOOP = 1000;public static void main(String[] args) throws InterruptedException {final Counter counter = new Counter();Thread t1 = new Thread(){@Overridepublic void run() {for(int i = 0; i < LOOP; i++){counter.add(1);}}};Thread t2 = new Thread(){@Overridepublic void run() {for(int i = 0; i < LOOP; i++){counter.dec(1);}}};t1.start();t2.start();t1.join();t2.join();System.out.println(counter.get());System.out.println("END");} }使用tryLock()可指定超時:
public void inc() throws InterruptedException {if(lock.tryLock(1, TimeUnit.SECONDS)){try{this.value += 1;}finally {lock.unlock();}} }ReentrantLock可以替代synchronized
ReentrantLock獲取鎖更安全
必須使用try.. finally保證正常獲取和釋放鎖
?
源碼下載地址:
https://github.com/fengfanchen/Java/tree/master/javaMuObject
總結
以上是生活随笔為你收集整理的Java笔记-多线程协调及ReentrantLock的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot通过@Reques
- 下一篇: java美元兑换,(Java实现) 美元