Meho HoMe Hatić Meho HoMe Hatić - 7 months ago 12
Java Question

Cannot .stop() .wait() or stop the thread in any way

I am having troubles with stopping a thread which is started from outside the class using a actionPerformed on a JButton. Code of the thread class below.

public synchronized void run ()
{
try
{
do
{
int minuta = vrijeme / 60;
int sekundi = vrijeme % 60;

System.out.println(minuta+" "+sekundi);

vrijeme = vrijeme - 1;
delay = delay - 1000;

if (minuta == stani && sekundi == 0)
{

}



try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (delay != 0);
{
//
}
}
catch (Exception e)
{
System.out.println("Stao" + e);
}
}
void pokreniThread()
{
(new Thread(new OdredenoVrijeme())).start();
}
synchronized public void zaustaviThread()
{
try
{
(new Thread(new OdredenoVrijeme())).wait();
}
catch (Exception e)
{
System.out.println("stao" +e);
}
}


}

Every time i call .sleep() .wait() or anything similar i get the following catch message:

java.lang.IllegalMonitorStateException

Answer

Under Java, you cannot have a sleep in the main process. Create a sub-thread, which will do the sleep, then post a message to a handler in the main-thread, to do something after the timeout.

If you want to stop a thread itself, set a variable inside the thread like is_stopping=true, then inside the thread you could set a variable is_running=false after the thread stops itself.

is_running=true;
while (is_running & !is_stopping)
{
   do_something();
   sleep();
}
is_stopping=false;
is_running=false;
Comments