-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReader_Writer_Semaphore.java
75 lines (67 loc) · 2.34 KB
/
Reader_Writer_Semaphore.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
import java.util.concurrent.Semaphore;
class ReaderWritersProblem {
static Semaphore readLock = new Semaphore(1);
static Semaphore writeLock = new Semaphore(1);
volatile static int readCount = 0;
static class Read implements Runnable {
@Override
public void run() {
try {
readLock.acquire();
synchronized(ReaderWritersProblem.class) {
readCount++;
}
if (readCount == 1) {
writeLock.acquire();
}
readLock.release();
System.out.println("Thread "+Thread.currentThread().getName() + " is READING");
Thread.sleep(1500);
System.out.println("Thread "+Thread.currentThread().getName() + " has FINISHED READING");
readLock.acquire();
synchronized(ReaderWritersProblem.class) {
readCount--;
}
if(readCount == 0) {
writeLock.release();
}
readLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
static class Write implements Runnable {
@Override
public void run() {
try {
writeLock.acquire();
System.out.println("Thread "+ Thread.currentThread().getName() + " is WRITING");
Thread.sleep(2500);
System.out.println("Thread "+ Thread.currentThread().getName() + " has finished WRITING");
writeLock.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) throws Exception {
Read read = new Read();
Write write = new Write();
Thread t1 = new Thread(read);
t1.setName("thread1");
Thread t2 = new Thread(read);
t2.setName("thread2");
Thread t3 = new Thread(write);
t3.setName("thread3");
Thread t4 = new Thread(read);
t4.setName("thread4");
Thread t5 = new Thread(write);
t5.setName("thread5");
t1.start();
t3.start();
t2.start();
t4.start();
t5.start();
}
}