-
Notifications
You must be signed in to change notification settings - Fork 0
/
Threads_and_Synchronization_2.java
417 lines (351 loc) · 13 KB
/
Threads_and_Synchronization_2.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package sync2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.Semaphore;
/**
*
* @author ristes
*/
public class TemplateNumRunsAndNumInstances {
//TODO: definirajte gi semaforite i ostanatite promenlivi ovde (mora site da se static)
static int brKlienti;
static boolean isAsleep;
static Semaphore wakeUp;
static Semaphore done;
static Semaphore klientNadvor;
static Semaphore klientVnatre;
static Semaphore proverka;
/**
* Metod koj treba da gi inicijalizira vrednostite na semaforite i
* ostanatite promenlivi za sinhronizacija.
*
*
* TODO: da se implementira
*
*/
public static void init(int numBarbers) {
brKlienti = 0;
isAsleep = true;
wakeUp = new Semaphore(0);
done = new Semaphore(0);
klientNadvor = new Semaphore(0);
klientVnatre = new Semaphore(0);
proverka = new Semaphore(1);
}
static class Barber extends TemplateThread {
public int barberId;
public Barber(int numRuns, int barberId) {
super(numRuns);
this.barberId = barberId;
}
/**
* Da se implementira odnesuvanjeto na berberot spored baranjeto na
* zadacata.
*
*
* TODO: da se implementira
*
*/
public void execute() throws InterruptedException {
// koga 5tiot klient ke notificira, berberot treba da se razbudi
if(isAsleep) {
wakeUp.acquire();
state.barberWakeUp();
isAsleep = false;
}
// koga klientot ke pristigne, go vika klientot da vleze
state.barberCallCustomer();
klientNadvor.release();
klientVnatre.acquire();
// koga klientot ke vleze, go potstrizuva
state.cutHair();
done.release();
// proveruva dali ima klienti koi cekaat, ako nema, zaspiva
proverka.acquire();
brKlienti--;
if(brKlienti == 0) {
proverka.release();
isAsleep = true;
state.barberGoToSleep();
}
else {
proverka.release();
}
}
}
static class Consumer extends TemplateThread {
public Consumer(int numRuns) {
super(numRuns);
}
/**
* Da se implementira odnesuvanjeto na ucesnikot spored uslovite na
* zadacata.
*/
public void execute() throws InterruptedException {
state.customerArrived();
proverka.acquire();
// dokolku e pettiot, go budi berberot
if(brKlienti == 5 && isAsleep) {
wakeUp.release();
}
proverka.release();
// koga ke bide povikan, vleguva
klientNadvor.acquire();
state.customerEntry();
// klientot vlegol vo berbernicata i e spremen za potstrizuvanje
klientVnatre.release();
// koga ke go potstrizat, plakja
done.acquire();
state.customerPay();
}
}
//<editor-fold defaultstate="collapsed" desc="This is the template code" >
static State state;
static class State {
private static final Random RANDOM = new Random();
private static final int RANDOM_RANGE = 5;
private final int numBarbers;
private boolean barberWaked[];
public State(int numBarbers) {
this.numBarbers = numBarbers;
barberWaked = new boolean[numBarbers];
}
private int arrivedCustomers = 0;
private int calledCustomers = 0;
private int maxCuttings = 0;
private int numCuttings = 0;
public synchronized void customerArrived() throws RuntimeException {
log(null, "customer arrived");
arrivedCustomers++;
}
public synchronized void barberWakeUp() throws RuntimeException {
Barber b = (Barber) Thread.currentThread();
if (barberWaked[b.barberId]) {
PointsException e = new PointsException(5, "Berberot e veke buden i nema potreba da se razbudi.");
log(e, null);
} else {
log(null, "the barber is waked up");
barberWaked[b.barberId] = true;
}
}
public synchronized void barberCallCustomer() throws RuntimeException {
log(null, "the barber calls the customer");
if (arrivedCustomers <= 0) {
PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da bide povikan.");
log(e, null);
}
calledCustomers++;
}
public synchronized void customerEntry() throws RuntimeException {
log(null, "customer sits in the chair");
if (arrivedCustomers <= 0) {
PointsException e = new PointsException(5, "Brojot na klienti koi cekaat e 0 i nema koj da vleze.");
log(e, null);
}
if (calledCustomers <= 0) {
PointsException e = new PointsException(5, "Nema povikano klient i ne moze da vleze.");
log(e, null);
}
arrivedCustomers--;
calledCustomers--;
numCuttings++;
}
public void cutHair() throws RuntimeException {
synchronized (this) {
if (numCuttings <= 0) {
PointsException e = new PointsException(5, "Nema prisuten klient za potstrizuvanje");
log(e, null);
}
log(null, "berber cuts the customer hair");
}
try {
int r;
synchronized (this) {
r = RANDOM.nextInt(RANDOM_RANGE);
}
Thread.sleep(r);
} catch (Exception e) {
//do nothing
}
synchronized (this) {
if (numCuttings <= 0) {
PointsException e = new PointsException(5, "Brojot na klienti koi se strizat e 0 i nema koj da izleze.");
log(e, null);
}
numCuttings--;
}
}
public synchronized void customerPay() throws RuntimeException {
log(null, "customer is paying and leaving the shop");
}
public synchronized void barberGoToSleep() throws RuntimeException {
Barber b = (Barber) Thread.currentThread();
if (!barberWaked[b.barberId]) {
PointsException e = new PointsException(5, "Berberite veke spijat i ne moze da se prezaspijat.");
log(e, null);
}
if (arrivedCustomers > 0) {
PointsException e = new PointsException(5, "Seuste ima klienti koi cekaat i berberot ne moze da odi na spienje.");
log(e, null);
}
log(null, "all barbers go to sleap");
barberWaked[b.barberId] = false;
}
private List<String> actions = new ArrayList<String>();
private List<PointsException> exceptions = new ArrayList<PointsException>();
private synchronized void log(PointsException e, String action) {
TemplateThread t = (TemplateThread) Thread.currentThread();
if (e == null) {
actions.add(t.toString() + "\t(a): " + action);
} else {
t.setException(e);
actions.add(t.toString() + "\t(e): " + e.getMessage());
}
}
public synchronized void printLog() {
System.out.println("Poradi konkurentnosta za pristap za pecatenje, mozno e nekoja od porakite da ne e na soodvetnoto mesto.");
System.out.println("Log na izvrsuvanje na akciite:");
System.out.println("=========================");
System.out.println("tip\tid\titer\takcija/error");
System.out.println("=========================");
for (String l : actions) {
System.out.println(l);
}
}
public void printStatus() {
if (!TemplateThread.hasException) {
int poeni = 25;
if (PointsException.getTotalPoints() == 0) {
System.out.println("Procesot e uspesno sinhroniziran. Osvoeni 25 poeni.");
} else {
poeni -= PointsException.getTotalPoints();
PointsException.printErrors();
System.out.println("Osvoeni poeni: " + poeni);
}
} else {
System.out.println("Procesot ne e sinhroniziran spored uslovite na zadacata");
printLog();
System.out.println("====================================================");
PointsException.printErrors();
System.out.println("Maksimum Poeni: " + (25 - PointsException.getTotalPoints()));
}
}
}
abstract static class TemplateThread extends Thread {
static boolean hasException = false;
int numRuns = 1;
public int iteration = 0;
private Exception exception = null;
public TemplateThread(int numRuns) {
this.numRuns = numRuns;
}
abstract void execute() throws InterruptedException;
@Override
public void run() {
try {
for (int i = 0; i < numRuns && !hasException; i++) {
execute();
iteration++;
}
} catch (InterruptedException e) {
// Do nothing
} catch (Exception e) {
exception = e;
hasException = true;
}
}
public void setException(Exception exception) {
this.exception = exception;
hasException = true;
}
@Override
public String toString() {
Thread current = Thread.currentThread();
if (numRuns > 1) {
return String.format("%s\t%d\t%d", "" + current.getClass().getSimpleName().charAt(0), getId(), iteration);
} else {
return String.format("%s\t%d\t", "" + current.getClass().getSimpleName().charAt(0), getId());
}
}
}
static class PointsException extends RuntimeException {
private static HashMap<String, PointsException> exceptions = new HashMap<String, PointsException>();
private int points;
public PointsException(int points, String message) {
super(message);
this.points = points;
exceptions.put(message, this);
}
public static int getTotalPoints() {
int sum = 0;
for (PointsException e : exceptions.values()) {
sum += e.getPoints();
}
return sum;
}
public static void printErrors() {
System.out.println("Gi imate slednite greski: ");
for (Map.Entry<String, PointsException> e : exceptions.entrySet()) {
System.out.println(String.format("[%s] : (-%d)", e.getKey(), e.getValue().getPoints()));
}
}
public int getPoints() {
return points;
}
}
public static void main(String[] args) {
try {
start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void start() throws Exception {
Scanner s = new Scanner(System.in);
int brBarbers = s.nextInt();
int brKonzumeri = s.nextInt();
int numBarberRuns = s.nextInt();
int numCustomerRuns = s.nextInt();
init(brBarbers);
state = new State(brBarbers);
HashSet<Thread> threads = new HashSet<Thread>();
for (int i = 0; i < brBarbers; i++) {
Barber prod = new Barber(numBarberRuns, i);
threads.add(prod);
prod.start();
Consumer c = new Consumer(numCustomerRuns);
threads.add(c);
c.start();
}
for (int i = 0; i < brKonzumeri / 2 - brBarbers; i++) {
Consumer c = new Consumer(numCustomerRuns);
threads.add(c);
c.start();
}
try {
Thread.sleep(50);
} catch (Exception e) {
//do nothing
}
for (int i = 0; i < brKonzumeri / 2; i++) {
Consumer c = new Consumer(numCustomerRuns);
threads.add(c);
c.start();
}
for (Thread t : threads) {
t.join(1000);
}
for (Thread t : threads) {
if (t.isAlive()) {
t.interrupt();
}
}
state.printStatus();
}
//</editor-fold>
}