Java Thread - 如何使用ReentrantReadWriteLock
我們想知道如何使用ReentrantReadWriteLock。
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Main {
static final Main instance = new Main();
int counter = 0;
ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);
public void read() {
while (true) {
rwl.readLock().lock();
try {
System.out.println("Counter is " + counter);
} finally {
rwl.readLock().unlock();
}
try {
Thread.currentThread().sleep(1000);
} catch (Exception ie) {
}
}
}
public void write() {
while (true) {
rwl.writeLock().lock();
try {
counter++;
System.out.println("Incrementing counter. Counter is " + counter);
} finally {
rwl.writeLock().unlock();
}
try {
Thread.currentThread().sleep(3000);
} catch (Exception ie) {
}
}
}
public static void main(String[] args) {
instance.write();
instance.read();
}
}
運(yùn)行結(jié)果如下: