-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlave1.java
More file actions
73 lines (59 loc) · 1.74 KB
/
Slave1.java
File metadata and controls
73 lines (59 loc) · 1.74 KB
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
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Slave1 extends Thread {
private BlockingQueue<Packet> queue;
private ClientHandler clientHandler;
public Slave1() {
}
// Setter for ClientHandler
public void setClientHandler(ClientHandler clientHandler) {
this.clientHandler = clientHandler;
}
public void setQ(BlockingQueue<Packet> blockingQueue) {
this.queue = blockingQueue;
}
public String job1() throws InterruptedException {
Thread.sleep(2000);
return ("Executed operation 1 in slave 1");
}
// inefficient way to do job 2.
public String job2() throws InterruptedException {
Thread.sleep(10000);
return ("Executed operation 2 in slave 1");
}
public void setQueue(BlockingQueue<Packet> queue) {
this.queue = queue;
}
public BlockingQueue<Packet> getQueue() {
return queue;
}
@Override
public void run() {
System.out.println("Slave 1 started.");
while (true) { // Keep processing jobs from the queue
try {
// Take a job from the queue (blocks if the queue is empty)
Packet p = queue.take();
Operation operation = p.getOperation();
String result;
// Process the job based on its type
switch (operation) {
case JOB_1:
result = job1();
break;
case JOB_2:
result = job2();
break;
default:
result = "Unknown job type.";
}
clientHandler.updateCounterAfterCompletion(operation, 1); // Notify master to update counter
System.out.println("Slave 1 completed: " + result);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Slave interrupted: " + e.getMessage());
break; // Exit loop on interruption
}
}
}
}