I tried to let an applet wait it's execution at some point for a few
seconds. The code looks like this:
public class Applet1 extends Applet
{
public void init()
{
//...
stopApplet();
}
private synchronized void stopApplet()
{
Thread currentThread=Thread.currentThread();
debug("waiting for 3 seconds...");
try
{
currentThread.wait(3000);
}
catch (java.lang.InterruptedException e) {}
debug("... it's over.");
}
}
Can anybody please tell me, why I get the following error and what to do in
order to let the applet wait?
Thanks for your time, Holger
waiting for 3 seconds...
java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.wait(Native Method)
at Applet1.stopApplet(Applet1.java:48)
at Applet1.init(Applet1.java:37)
at sun.applet.AppletPanel.run(AppletPanel.java:333)
at java.lang.Thread.run(Thread.java:479)
The purpose of wait is to wait for someone else to notify the waiting
thread of an event, and since you are waiting on a newly created thread
without telling anyone about it, you are unlikely to get notified.
If you just want the thread you are running in to sleep for 3 seconds,
use Thread.sleep(3000).
Patricia
unless you need to notify that thread or it locks some synchronized clasess
you can use sleep(time)
"Holger Wiechert" <holger....@coconet.de> wrote in message
news:398aa3f7$1...@news.isis.de...
That's an incredibly misleading way to put it. Better is:
Thread.sleep(3000);
as sleep(long) and sleep(long,int) are static methods.
> "Holger Wiechert" <holger....@coconet.de> wrote in message
> news:398aa3f7$1...@news.isis.de...
> > private synchronized void stopApplet()
> > [...]
> > currentThread.wait(3000);
> > [...]
> > java.lang.IllegalMonitorStateException: current thread not owner
wait() is a method in Object. You need to synchronise to the same object
in order to wait or notify. So other than using sleep there are a number
of solutions available:
synchronized (currentThread) (
currentThread.wait(3000);
}
You probably don't want to synchronize onto your current thread.
wait(3000); // On this.
or
Object lock = new Object();
synchronized (lock) (
lock.wait(3000);
}
Probably best to use sleep(). Or better don't use multithreading at all.
Do a timed repaint() and check to see that the time has elapsed.
Threading is difficult, dangerous and can be resource intensive.
BTW: Never block in the AWT event dispatch thread, including file,
socket and URLConnection access but excluding guaranteed quick
synchronized blocks.
Tackline