forked from LuigiCortese/java-certification-ocp8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.java
81 lines (61 loc) · 1.73 KB
/
App.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package net.devsedge.lockandcondition.reentrantreadwritelock;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import net.devsedge.NameUtil;
import net.devsedge.Util;
/**
*
* @author Luigi Cortese
*
*/
public class App {
static NameUtil nameUtil;
static ReentrantReadWriteLock lock;
static{
nameUtil=new NameUtil(20);
lock=new ReentrantReadWriteLock();
}
public static void main(String[] args) {
Util.startTimer(10);
new Thread(new Reader()).start();
new Thread(new Reader()).start();
new Thread(new Reader()).start();
new Thread(new Writer()).start();
}
}
class Reader implements Runnable{
private String name=App.nameUtil.getName();
@Override
public void run() {
System.out.println(name+": waiting for R lock");
App.lock.readLock().lock();
System.out.println(name+": got R lock, reading");
try {
Thread.sleep(ThreadLocalRandom.current().nextLong(2000,6000));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
App.lock.readLock().unlock();
System.out.println(name+": releasing R lock");
}
System.out.println(name+": exiting");
}
}
class Writer implements Runnable{
private String name=App.nameUtil.getName();
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(name+": waiting for RW lock");
App.lock.writeLock().lock();
System.out.println(name+": got RW lock, writing");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
App.lock.writeLock().unlock();
System.out.println(name+": releasing WR lock");
}
}
}