以前的同步操作 基本上都是用到 synchronised 關(guān)鍵字,類似代碼如下:
synchronised(obj){
//dosomething...
}來做到同步,
在 JDK5.0 里面有這么一個(gè)對(duì)象,ReentrantLock,發(fā)覺她的加鎖編程的方式非常的適合日常的加鎖習(xí)慣,
EG:
package com.thread.synchronise;
import java.util.concurrent.locks.ReentrantLock;
public class SynchroTest extends Thread{
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void run()
{
//這里加了幾次鎖,在后面就的要相應(yīng)的解鎖 幾次
lock.lock(); // block until condition holds
try {
count++;
System.out.println(" count = "+count);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" count = "+count);
} finally {
lock.unlock();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SynchroTest st1 = new SynchroTest();
// SynchroTest st2 = new SynchroTest();
// SynchroTest st3 = new SynchroTest();
//這里不能夠調(diào)用 new Thread(st1).run();方法,否則就不是多線程的了
new Thread(st1).start();
new Thread(st1).start();
new Thread(st1).start();
}
}
如果該線程等待某暫時(shí)獲取不到的資源,那么我們可以用Condition Object來避免死鎖情況。
sufficientFunds = lock .newCondition();
如果條件不滿足:
sufficientFunds.await();
這時(shí)線程就會(huì)釋放鎖并進(jìn)入blocked狀態(tài),其他線程就有機(jī)會(huì)執(zhí)行操作。當(dāng)其他線程執(zhí)行完后,就可通知等待的線程繼續(xù)執(zhí)行它的操作了:
sufficientFunds.signalAll();