private final ReentrantReadWriteLock theLock = new ReentrantReadWriteLock();
private final Lock writeLock = theLock.writeLock();
private final Lock readLock = theLock.readLock();
能创建读锁和写锁,我搞不清楚读写锁的区别,分别用在什么场合,好像我全用读锁也能实现锁住方法
public static void main(String[] args) {
final Test t = new Test();
scheduledExecutor = new ScheduledThreadPoolExecutor(3);
scheduledExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
t.writeLock.lock();
t.print("test1111111111111");
t.writeLock.unlock();
} catch (Throwable t) {
}
}
}, 5, 10000, TimeUnit.SECONDS);
scheduledExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
t.readLock.lock();
t.print("test2222222222222222");
t.readLock.unlock();
} catch (Throwable t) {
}
}
}, 10, 1000, TimeUnit.SECONDS);
scheduledExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
t.writeLock.lock();
t.print("test33333333333");
t.writeLock.unlock();
} catch (Throwable t) {
}
}
}, 5, 10000, TimeUnit.SECONDS);
}
public void print(String s){
System.out.println(s);
while(true)
;
}
能保证一个时刻只有一个线程能进入此方法,到底读写锁有什么区别呢,什么时候用读的,什么时候用写的
[b]问题补充:[/b]
我试过,如果读锁被获取,试图获取读写锁都阻塞了.还有,有些情况是读写交错的,比如有一个方法,先是从库里读一些数据过来,然后,再写到数据库里.那么你说这时用读锁还是写锁.
[b]问题补充:[/b]
这遍文章我看过,我不明白,具体在什么时候用读写锁