更新时间:2022-06-26 01:22:09
在SQLite的,可以有任意多的读者,但是任何作家阻止所有其他读者和作者。
In SQLite, there can be arbitrarily many readers, but any writer blocks all other readers and writers.
您要为读者和作者使用一个锁。
You have to use a single lock for both readers and writers.
请注意,必须先把锁,只要你实际上是在访问数据库中保存。
Please note that locks must be held as long as you're actually accessing the database.
如果你想支持多个阅读器,使用实现ReadWriteLock$c$c>,如ReentrantReadWriteLock$c$c>.事情是这样的:
If you want to support multiple readers, use a lock that implements ReadWriteLock
, such as ReentrantReadWriteLock
. Something like this:
class MyData {
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock r = rwl.readLock();
private final Lock w = rwl.writeLock();
public Data ReadSomething(int id) {
r.lock();
try {
Cursor c = readableDatabase.query(...);
return c.getString(0);
} finally {
r.unlock();
}
}
public void ChangeSomething(int id, int value) {
w.lock();
try {
writeableDatabase.update(...);
} finally {
w.unlock();
}
}
}