-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMultiThreading.java
108 lines (92 loc) · 2.93 KB
/
MultiThreading.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// extends runnable
class PrintSequenceRunnable implements Runnable {
public static final int PRINT_LIMIT = 9;
static final Lock lock = new Lock();
static char[] values = new char[]{'A', 'B', 'C'};
int sequence;
PrintSequenceRunnable(int sequence) {
this.sequence = sequence;
}
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i < PRINT_LIMIT; i++) {
while (lock.number % 3 != sequence) { // wait for numbers other than remainder
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(values[sequence]);
lock.number++;
lock.notifyAll();
}
}
}
}
// using update shared status in lock object
class Lock {
volatile int status = 0;
volatile int number = 0;
}
class SequentialPrint extends Thread {
static char[] values = new char[]{'A', 'B', 'C'};
final Lock lock;
public int PRINT_LIMIT;
int printSequence;
SequentialPrint(Lock lock, int printSequence, int PRINT_LIMIT) {
this.lock = lock;
this.printSequence = printSequence;
this.PRINT_LIMIT = PRINT_LIMIT;
}
SequentialPrint(Lock lock, int printSequence) {
this(lock, printSequence, 9);
}
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i < PRINT_LIMIT; i++) {
while (lock.status != printSequence) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(values[printSequence]);
lock.status = (printSequence + 1) % 3;
lock.notifyAll();
}
}
}
}
public class MultiThreading {
public static void main(String[] args) throws InterruptedException {
PrintSequenceRunnable runnable1 = new PrintSequenceRunnable(0);
PrintSequenceRunnable runnable2 = new PrintSequenceRunnable(1);
PrintSequenceRunnable runnable3 = new PrintSequenceRunnable(2);
Thread t1 = new Thread(runnable1);
Thread t2 = new Thread(runnable2);
Thread t3 = new Thread(runnable3);
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
System.out.println();
System.out.println();
Lock lock = new Lock();
SequentialPrint a = new SequentialPrint(lock, 0);
SequentialPrint b = new SequentialPrint(lock, 1);
SequentialPrint c = new SequentialPrint(lock, 2);
a.start();
b.start();
c.start();
a.join();
b.join();
c.join();
System.out.println("\n");
}
}