@Ramya: your way will terminate the thread, not wait like he wants.
This one has pseudocode interspersed in it, but should work. I did extend thread, but the difference should not matter that much.
|
Code:
|
public class AnimThread extends Thread{
private boolean terminate=false, waitFlag=false, inSleepOrWait=false;
private Object wait=new Object;
public AnimThread(){
super("Animation Thread);//Always name threads!!!
//Thread names appear in runtime exceptions, and can be useful in tracking down the bug
//This is especially important if you are going to use a debugger
}
public void run(){
//I'm leaving out your actual animation
while(!terminate){
//do animation
try{
inSleepOrWait=true;
sleep(100);
} catch (InterruptedException ie){
return;
}
if(waitFlag){
try{
wait.wait();
} catch(InterruptedException ie){
return;
}
}
inSleepOrWait=false;
}
}
public void terminate(){
if(inSleepOrWait)
interrupt();
else terminate=true;
}
public void halt(){
waitFlag=true;
}
public void continue(){
waitFlag=false;
wait.notifyAll();
}
} |
Also, instead of just calling system.exit(0) when the exit button is pressed, try this... It ensures that your thread gets terminated "normally" rather than abruptly closing, or worse, getting stuck.
|
Code:
|
final AnimThread at = new AnimThread();
.....
if(e.getSource()==bexit)
at.terminate();
System.exit(0);
} |
EDIT: Missed OPs last post, though I still think this could be a better way of doing it.
The flaw in the logic was that a thread can ignore the interrupt() method. To ensure that the thread is terminated, you need to use some form of flag.