This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSynchronizedTraffic.java
70 lines (50 loc) · 2.59 KB
/
SynchronizedTraffic.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
import java.util.concurrent.Semaphore;
/**
* @author Derek Campbell (DLB832)
* @version 3/27/2021
* NOTE: CPSC.2800.20473
*
*/
public class SynchronizedTraffic {
Semaphore bridge = new Semaphore(1, true); //only 1 resource or permit available at time. gairness set to true.
final int NUM_CARS = 5; //the number of cars in each thread (or each side of the bridge).
//TODO: create threads. 1 thread should simulate east bound vehicles and 1 simulate west bound vehicles.
/*Vehicles should wait(sleep) for some time, then attempt to cross.
* once on the bridge it should sleep for some time to simulate traveling over the bridge.
* output a message when a vehicle drives onto the bridge and another when it has completed crossing.
*/
//creating java threads: define a class that implements the runnable interface.
class Car implements Runnable { //each car is a thread which overrides the default run().
public void run() {
try {
bridge.acquire(); //acquires semaphore, providing mutual exclusion
System.out.println("Car: " + Thread.currentThread().getName() + " has enterred the bridge."); //TODO: determine which car it is.
Thread.sleep(3000); //sleep to simulate crossing the bridge
System.out.println("Car: " + Thread.currentThread().getName() + " has successfully crossed the bridge and exited.");
} catch (Exception e) {
//TODO: handle exception
//if busy, blocked
} finally {
bridge.release(); //placed in finally to ensure that semaphore is released
}
}
}
/* thread creation in java involves creating a Thread object and passing it an instance of a class that implements
* Runnable, followed by invoking the start() method on the Thread object.
* TODO: create eastBound and westBound cars.
*/
public static void main(String[] args) {
final int NUM_CARS = 5;
SynchronizedTraffic syncTraf = new SynchronizedTraffic();
Thread[] eastBoundCars = new Thread[NUM_CARS]; //creates an array of threads for east bound cars
for (int i = 0; i < eastBoundCars.length; i++) {
eastBoundCars[i] = new Thread(new syncTraf.Car());
eastBoundCars[i].start();
}
Thread[] westBoundCars = new Thread[NUM_CARS]; //creates an array of threads for west bound cars
for (int i = 0; i < westBoundCars.length; i++) {
westBoundCars[i] = new Thread(new Car());
westBoundCars[i].start();
}
}
}