[英]block current thread for executing, until a variable is updated by another thread
我的代碼:
private AtomicBoolean fetched1 = new AtomicBoolean(false);
private int rowCount;
public int getRowCount() {
data.getRealm().exec(new Runnable(){
@Override
public void run() {
rowCount = data.size();
fetched1.set(true);
}
});
while(!fetched1.get()){
}
fetched1.set(false);
return rowCount;
}
它現在似乎對我有用,但我不熟悉線程(它總是讓我困惑),我應該像上面的代碼那樣做嗎?
我應該像上面的代碼那樣做嗎?
這看起來是一個旋轉循環,將使用不必要的CPU。 最好使用wait
和notify
來表示數據已被提取。 就像是:
private final Object lock = new Object();
private volatile Integer rowCount = null;
...
public void run() {
rowCount = data.size();
synchronized (lock) {
lock.notify();
}
}
synchronized (lock) {
// we loop here in case of race conditions or spurious interrupts
while (rowCount == null) {
lock.wait();
}
}
...
我認為你根本不需要獲取AtomicBoolean
。 您應該使rowCount
變為volatile
,然后您可以測試其值。 由於生產者/消費者的競爭條件和虛假中斷, while
循環是一個很好的模式。
你有兩個問題
相反,最簡單的模式是鎖定對象並在值更改時等待/通知。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.