并發包結構圖:
編寫一個自定義同步組件來加深對同步器的理解
業務要求:
* 編寫一個自定義同步組件來加深對同步器的理解。
* 設計一個同步工具:該工具在同一時刻,只允許至多兩個線程同時訪問,超過兩個線程的
* 訪問將被阻塞,我們將這個同步工具命名為TwinsLock。
* 首先,確定訪問模式。TwinsLock能夠在同一時刻支持多個線程的訪問,這顯然是共享式
* 訪問,因此,需要使用同步器提供的acquireShared(int args)方法等和Shared相關的方法,這就要
* 求TwinsLock必須重寫tryAcquireShared(int args)方法和tryReleaseShared(int args)方法,這樣才能
* 保證同步器的共享式同步狀態的獲取與釋放方法得以執行。
* 其次,定義資源數。TwinsLock在同一時刻允許至多兩個線程的同時訪問,表明同步資源
* 數為2,這樣可以設置初始狀態status為2,當一個線程進行獲取,status減1,該線程釋放,則
* status加1,狀態的合法范圍為0、1和2,其中0表示當前已經有兩個線程獲取了同步資源,此時
* 再有其他線程對同步狀態進行獲取,該線程只能被阻塞。在同步狀態變更時,需要使用
* compareAndSet(int expect,int update)方法做原子性保障。
* 最后,組合自定義同步器。前面的章節提到,自定義同步組件通過組合自定義同步器來完
* 成同步功能,一般情況下自定義同步器會被定義為自定義同步組件的內部類
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class TwinsLock implements Lock {
private final Sync sync = new Sync(2);
private static final class Sync extends AbstractQueuedSynchronizer {
Sync(int count) {
if(count <= 0) {
throw new IllegalArgumentException("count must large zero!");
}
setState(count);
}
//共享式同步狀態的獲取。
public int tryAcquireShared(int reduceCount) {
for(;;) { //自旋
int current = getState();
int newCount = current - reduceCount;
if(newCount < 0 || compareAndSetState(current, newCount)) {
return newCount;
}
}
}
//共享式同步狀態釋放.
public boolean tryReleaseShared(int returnCount) {
for(;;) {//自旋.
int current = getState();
int newCount = current + returnCount;
if(compareAndSetState(current, newCount)) {
return true;
}
}
}
final ConditionObject newCondition() {
return new ConditionObject();
}
}
//共享式獲取
public void lock() {
sync.acquireShared(1);
}
public void lockInterruptibly() throws InterruptedException {
//和acquire方法相同, 但是該方法響應中段.
sync.acquireInterruptibly(1);
}
//如果返回大于等于0表示獲取成功。
public boolean tryLock() {
return sync.tryAcquireShared(1) >= 0;
}
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
}
//釋放所資源
public void unlock() {
sync.releaseShared(1);
}
public Condition newCondition() {
return sync.newCondition();
}
}
import javafx.concurrent.Worker;
import java.util.concurrent.locks.Lock;
public class TwinsLockTest {
public static void main(String argc[]){
final Lock lock = new TwinsLock();
class Worker extends Thread{
public void run() {
while(true) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(1500);
} catch (InterruptedException e) {
System.out.println("interruptException!");
}
finally {
lock.unlock();
break;
}
}
}
}
for(int i = 0; i < 10; i++) {
Worker worker = new Worker();
//worker.setDaemon(true);
worker.start();
}
//每間隔一秒鐘打印一個空行.
for(int i = 0; i <10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
}
}
}