-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathParking.java
66 lines (49 loc) · 1.82 KB
/
Parking.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
package com.sergeyvolkodav.concurrency.synchronizers.semaphore;
import java.util.concurrent.Semaphore;
/**
*
*/
public class Parking {
// Parking place occupied = true; free - false
private static final boolean[] PARKING_PLACES = new boolean[5];
private static final Semaphore SEMAPHORE = new Semaphore(5, true);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 7; i++) {
new Thread(new Car(i)).start();
Thread.sleep(500);
}
}
public static class Car implements Runnable {
private int carNumber;
public Car(int carNumber) {
this.carNumber = carNumber;
}
@Override
public void run() {
System.out.printf("Car #%d drive to parking \n", carNumber);
try {
SEMAPHORE.acquire();
int parkingNumber = -1;
synchronized (PARKING_PLACES) {
for (int i = 0; i < 5; i++) {
if (!PARKING_PLACES[i]) {
PARKING_PLACES[i] = true;
parkingNumber = i;
System.out.printf("Car #%d Parked on %d place.\n", carNumber, i);
break;
}
}
}
//Shopping!
Thread.sleep(5000);
synchronized (PARKING_PLACES) {
//Free space for car
PARKING_PLACES[parkingNumber] = false;
}
SEMAPHORE.release();
System.out.printf("Car #%d leave the parking.\n", carNumber);
} catch (InterruptedException e) {
}
}
}
}