Hi all,
I have an assignment due tomorrow and I really need your help. I have the program code and according to the assignment I need to change it to make it working according to part (a) and( b). I am really confused how to implement this thread program. Here is the code.
class Task {
String task;
public Task(String task) { this.task = task; }
public String toString() { return task; } }
class Boss {
Secretary secretary;
Boss(Secretary secretary) { this.secretary = secretary; }
void work() {
secretary.receive(new Task("(boss) write a letter"));
secretary.receive(new Task("(boss) clean my desk")); }}
class Student {
Secretary secretary;
Student(Secretary secretary) { this.secretary = secretary; }
void work() {
secretary.receive(new Task("(student) Do my homework"));
secretary.receive(new Task("(student) proof-read my assignment")); } }
class Secretary {
java.util.ArrayList<Task> tasks = new java.util.ArrayList<Task>();
public void receive(Task task) {
tasks.add(task); }
public void goToWork() {
while(true) {
if(tasks.size() > 0) {
Task t = tasks.remove(0);
System.out.println("working on '" + t + "'..");
try { Thread.sleep(1000); }catch(InterruptedException e){}
System.out.println(tasks.size() + " tasks left...");
}
}
}
public static void main(String[] args) {
Secretary jane = new Secretary();
Student john = new Student(jane);
Boss mrDoe = new Boss(jane);
john.work();
mrDoe.work();
jane.goToWork();
john.work();
mrDoe.work();
}
}
(a) Change the code to use separate threads for the secretary and a student and a boss giving her assignments at random intervals. Argue for each method you synchronize, and each place you use a synchronized block. Remember that just because the program does as you expect, it is not a guarantee that it is thread safe.
(b) Enhance the code such that if there are no jobs for the secretary she will wait() for jobs
I really appreciate your help. Looking forward to your reply.
Koonda