-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathElevator.cs
120 lines (109 loc) · 3.44 KB
/
Elevator.cs
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
using System;
using System.Collections.Generic;
using System.Threading;
namespace ElevatorSystem
{
public class Elevator
{
private readonly int id;
private readonly int capacity;
private int currentFloor;
private Direction currentDirection;
private readonly List<Request> requests;
public Elevator(int id, int capacity)
{
this.id = id;
this.capacity = capacity;
this.currentFloor = 1;
this.currentDirection = Direction.UP;
this.requests = new List<Request>();
}
public void AddRequest(Request request)
{
lock (requests)
{
if (requests.Count < capacity)
{
requests.Add(request);
Console.WriteLine("Elevator " + id + " added request: Source " + request.SourceFloor + " -> Destination " + request.DestinationFloor);
Monitor.PulseAll(requests); // Notify waiting threads
}
}
}
public Request GetNextRequest()
{
lock (requests)
{
while (requests.Count == 0)
{
try
{
Monitor.Wait(requests); // Wait for a new request
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
Request nextRequest = requests[0];
requests.RemoveAt(0);
return nextRequest;
}
}
public void ProcessRequests()
{
while (true)
{
while (requests.Count > 0)
{
Request request = GetNextRequest();
ProcessRequest(request);
}
lock (requests)
{
try
{
Monitor.Wait(requests); // Wait for new requests
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
}
}
private void ProcessRequest(Request request)
{
int startFloor = currentFloor;
int endFloor = request.DestinationFloor;
if (startFloor < endFloor)
{
currentDirection = Direction.UP;
for (int i = startFloor; i <= endFloor; i++)
{
currentFloor = i;
Console.WriteLine("Elevator " + id + " reached floor " + currentFloor);
Thread.Sleep(1000); // Simulating elevator movement
}
}
else if (startFloor > endFloor)
{
currentDirection = Direction.DOWN;
for (int i = startFloor; i >= endFloor; i--)
{
currentFloor = i;
Console.WriteLine("Elevator " + id + " reached floor " + currentFloor);
Thread.Sleep(1000); // Simulating elevator movement
}
}
}
public void Run()
{
ProcessRequests();
}
public int CurrentFloor
{
get { return currentFloor; }
}
}
}