亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請問下這個做用是什么?Condition用來干嘛的?

請問下這個做用是什么?Condition用來干嘛的?

溫溫醬 2023-03-03 13:09:27
private Lock lock = new ReentrantLock();private Condition threadCond = lock.newCondition();
查看完整描述

1 回答

?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

1、在某些情況下,當內部鎖非常不靈活時,顯式鎖就可以派上用場。內部條件隊列有一些缺陷,每個內部鎖只能有一個與之相關聯的條件隊列。

2、使用顯式的Lock和Condition的實現類提供了一個比內部鎖和條件隊列更加靈活的選擇。一個Condition和一個單獨的Lock相關聯,就像條件隊列和單獨的內部鎖相關聯一樣。每個鎖可以有多個等待集、中斷性選擇、基于時限、公平性選擇等。

public interface Condition{

void await() throws InterruptedException;//相當于wait

boolean await(long time,TimeUnit unit) throws InterruptedException;

long awaitNanos(long nanosTimeout) throws InterruptedException;

void awaitUninterruptibly();

boolean awaitUntil(Date deadline) throws InterruptedException;

void signal();//相當于notify

void signalAll();//相當于notifyall

}

調用與Condition相關聯的Lock的Lock.newCondition方法,可創建一個Condition.

3、有限緩存操作

@ThreadSafe

public class ConditionBoundedBuffer<T>{

protected final Lock lock=new ReentrantLock();

private final Condition notFull=lock.newCondition();

private final Condition notEmpty=lock.newCondition();

@GuardBy("lock");

private final T[] items=(T[]) new Object[BUFFER_SIZE];

@GuardBy("lock") private int tail,head,count;

public void put(T x) throws InterruptedExceptoin{

lock.lock();

try{

while (count=items.lentgh)

notFull.await();

items[tail]=x;

if (++tail=items.length)

tail=0;

++count;

notEmpty.signal();

}

finally{lock.unlock();

}

}

public T take() throws InterruptedException{

lock.lock();

try{

while (count=items.lentgh)

notEmpty.await();

T x=items[head];

items[head]=null;

if (++head=items.length)

head=0;

--count;

notFull.signal();

return x;

}

finally{lock.unlock();

}

}
}

 


查看完整回答
反對 回復 2023-03-06
  • 1 回答
  • 0 關注
  • 88 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號