Here is an exam question I scored badly in before but am trying to get it right this time around. I would appreciate if somebody could point me in the right direction, thanks.
My questions is, is the provided solution in any way correct to solve the problem? How could it be improved.
My code follows the question.
Question:
An event object has one of two states signaled or non-signaled. When
the event is in the signaled state all or one waiting threads are
released. When it is reset to the non-signaled state all the user
threads will be forced to wait. An event stays in the signaled state
until it is reset to the non-signaled state. The basic idea is that
one or more threads can wait for some event to happen. When the event
waited for occurs the threads take whatever action is required. Using
wait/notify write an Event class.
My Attempt:
class Event {
boolean signal;
String obj = new String();
public Event(boolean signal) {
this.signal = signal;
}
synchronized void getSignal(){
while(!signal)
try{
wait();
}
catch(InterruptedException e) {}
}
public void setSignal(boolean signal) {
synchronized (this) {
this.signal = signal;
this.notifyAll();
}
}
}
I made this test class which I think answers the subject, and my Event is somehow similar to yours.
A thread is waiting for the event to happened (when signaled), then wait for the reset while another thread is activating and deactivating the signal, from time to time.
Edit: I wasn’t aware of your simple question so maybe this code is useless for you.
Anyway, your Event class should work, so what can I say ?