Reputation: 613
This is my Question
A health center has employed two doctors that examine and treat at most 25 patients in a day. A patient is examined and treated by any one of the two doctors. Each patient has to register his name so that the doctors can examine and treat the patient on first-come-first-serve bases.
Exercise 2 Part a: For the scenario2 mentioned above, develop a program that creates patients and doctors (both are threads). Patients register in a queue and the doctors pick patient from the same queue on first-come-first-serve bases and examine and treat them. Use the queue that is not thread safe (For example ArrayDeque). Make sure your program has no synchronization issues.
Part b: Use the queue that is thread safe (For example, ArrayBlockedQueue) and check if your solution has synchronization issues. (Make sure that you solution does not provide synchronized methods or synchronized blocks)
This is my CODE
package lab8;
import java.util.ArrayDeque;
public class LAB8 {
class Doctor implements Runnable {
private String name;
private Patient patient;
Doctor (String n){
name = n;
}
public void examine (){
System.out.println("Doctor is now examining the patient");
}
public void treat(){
System.out.println("Doctor is now treating the patient");
}
@Override
public void run (){
}
}
static class Patient implements Runnable {
private String name;
Patient (String n){
name = n;
}
public void register(String name){
System.out.println(name + " is registering in Queue");
}
@Override
public void run(){
ArrayDeque<Patient> Patients = new ArrayDeque(25);
for(int i = 0;i<25;i++){
Patients.add(new Patient("Patient No " + i));
Patients.removeFirst().register("Patient No " + i);
}
}
}
public static void main(String[] args) {
ArrayDeque<Patient> Patients = new ArrayDeque(25);
for(int i = 0;i<25;i++){
(new Thread (Patients.removeFirst())).start();
}
}
}
This is the error I am getting when I run it.
Exception in thread "main" java.util.NoSuchElementException at java.util.ArrayDeque.removeFirst(ArrayDeque.java:278) at lab8.LAB8.main(LAB8.java:50) Java Result: 1
I am only trying Part A right now.
Upvotes: 1
Views: 1140
Reputation: 5794
In your main function, the Patients
ArrayDeque object has no Patient objects. Rather it is empty, so there is nothing to remove from the queue. You need to add some Patients first.
ArrayDeque<Patient> Patients = new ArrayDeque(25);
for(int i = 0;i<25;i++){
(new Thread (Patients.removeFirst())).start();
}
You would need to add new Patients to the Patients
ArrayDeque first like you do here.
Patients.add(new Patient("Patient No " + i));
So you have have something like this...
public static void main(String[] args) {
ArrayDeque<Patient> Patients = new ArrayDeque(25);
for(int i = 0;i<25;i++){
Patient p = new Patient("Patient No " + i);
(new Thread (p)).start();
Patients.add(p);
}
}
Upvotes: 0