Hi all,
I have written a program which successfully uses threads to run an iteration
whilst at the same time responding to input from a simple GUI. However i
need to rewrite it without using suspend() and resume() to avoid deadlocks.
The 2 threads start fine, and i can use a button event in the GUI thread to
pause the iteration thread using wait(). However whatever i try i cannot
make the button rewake the iteration thread using notify().
I'll paste the critical parts of the code below, any help very much
appeciated here!
Thanks
Mark
///////////////////////////////// DECLARING THREAD & BOOLEAN
private Thread iteration_thread = new Thread(this);
private volatile boolean threadSuspended;
//////////////////////////////////////////////////////////////// TOGGLE
BUTTON
toggleButton = new Button("Toggle");
toggleButton.addActionListener(new ActionListener()
{
public synchronized void actionPerformed(ActionEvent e)
{
if(!iteration_thread.isAlive()) iteration_thread.start();
else
{
threadSuspended = !threadSuspended;
if (!threadSuspended)
{
notify();
}
}
}
});
///////////////////////////////////////////////// THE THREAD'S RUN METHOD
public void run()
{
while (true)
{
try
{
Thread.currentThread().sleep(500);
synchronized(this)
{
while(threadSuspended)
{
wait();
}
}
System.out.println("here"); // what to do when not paused
}
catch(InterruptedException e)
{
}
}
}
Mark \(UK\) - 07 May 2004 15:27 GMT
Mark (UK) wrote:
> Hi all,
>
[quoted text clipped - 12 lines]
>
> Mark
[code removed - see 1st post]
ok i've investigated some more, and i think the problem might be do do with
thread owenership? If i change notify() to iteration_thread.notify() I get
the error: "java.lang.IllegalMonitorStateException: current thread not
owner".
Any ideas?
Cheers
Mark \(UK\) - 07 May 2004 16:49 GMT
Mark (UK) wrote:
> Mark (UK) wrote:
>> Hi all,
[quoted text clipped - 24 lines]
>
> Cheers
It's ok I solved it, had to move the notify() out from the event handler
into a new method.