首页 新闻 会员 周边 捐助

java怎么设置获取读写锁超时时间

0
[已解决问题] 解决于 2012-02-09 17:39

获取读写锁read.lock()/write.lock()的时候如果别的对象正在持有,怎么能给它设置一个等待时间,超出等待时间就返回,不要一直等待,在C#里有一个ReaderWriterLock.AcquireReaderLock(milliTimeOut)方法可以实现,java里有没有类似的方法,或者怎么能实现一下。。。望各路高手们指点一下。。。

public class UpgradeLock{
private UpgradeLock()
{
}
private final ReadWriteLock rwlock =new ReentrantReadWriteLock();
private final Lock read=rwlock.readLock();
private final Lock write=rwlock.writeLock();

public boolean getReadLock()
{
try{
read.lock();
}catch(Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
public boolean getWriteLock()
{
try
{
write.lock();
}
catch (Exception e)
{
return false;
}
return true;
}
}
pm8:鉡的主页 pm8:鉡 | 初学一级 | 园豆:200
提问于:2012-01-11 20:01
< >
分享
最佳答案
0
 1 package bing.test;
2
3 import java.util.concurrent.locks.Lock;
4 import java.util.concurrent.locks.ReadWriteLock;
5 import java.util.concurrent.locks.ReentrantReadWriteLock;
6
7 public class UpgradeLock{
8 private UpgradeLock(){ }
9 private final static ReadWriteLock rwlock =new ReentrantReadWriteLock();
10 private final static Lock read=rwlock.readLock();
11 private final static Lock write=rwlock.writeLock();
12
13
14 public static void main(String[] args){
15 log(getReadLock());
16 log(getWriteLock());
17 }
18
19
20 public static boolean getReadLock()
21 {
22 try{
23 int time = 0;
24 // 设置超时时间为5秒,获取Lock,
25 //如果返回false(即获取失败)则等待直到超时,然后返回获取lock的状态
26 while(!read.tryLock() && ++time < 5){
27 Thread.sleep(1000);
28 log(time);
29 }
30 return read.tryLock();
31 }catch(Exception e)
32 {
33 e.printStackTrace();
34 return false;
35 }
36 }
37 public static boolean getWriteLock()
38 {
39 try{
40 int time = 0;
41 // 设置超时时间为5秒,获取Lock,
42 //如果返回false(即获取失败)则等待直到超时,然后返回获取lock的状态
43 while(!write.tryLock() && ++time < 5){
44 Thread.sleep(1000);
45 log(time);
46 }
47 return read.tryLock();
48 }catch(Exception e)
49 {
50 e.printStackTrace();
51 return false;
52 }
53 }
54 public static void log(Object m){
55 System.out.println(m);
56 }
57 }

是这个样子么?

xiqobai | 菜鸟二级 |园豆:260 | 2012-01-20 09:50

更正下

 1     public static boolean getWriteLock()
2 {
3 try{
4 int time = 0;
5 // 设置超时时间为5秒,获取Lock,
6 //如果返回false(即获取失败)则等待直到超时,然后返回获取lock的状态
7 //更正为++time<=5
8 while(!write.tryLock() && ++time <= 5){
9 Thread.sleep(1000);
10 log(time);
11 }
12 // 更正为write
13 return write.tryLock();
14 }catch(Exception e)
15 {
16 e.printStackTrace();
17 return false;
18 }
19 }
xiqobai | 园豆:260 (菜鸟二级) | 2012-01-20 09:54
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册