java怎么设置获取读写锁超时时间
发布网友
发布时间:2022-04-28 20:59
我来回答
共1个回答
热心网友
时间:2022-06-23 04:30
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 }