Stop aktive Threads with AWT

Hi again.
I need to know how to interrupt actions of my program
with a simple AWT-Button.
I have a method running using the full CPU-power.
In it there’s a test if some boolean is still true, let’s call it “boolean running”.
When I press the “stop”-button which sets the boolean running to false, nothing happens and
the stop-button is pressed after the method is ready.
But I want to use the button to interrupt the method anytime.
I guess there has to be a simple solution.
Please help me.

Hiya, can you post the code?

My best guess is to declare the boolean variable as volatile, so that separate threads pick up the change immediately.

I’m assuming you periodically check the boolean in computing thread, and not just at the start, right?

also becarefull if you eat 100% cpu your button event can take age to be propagated (add a thread.yield() and/or sleep(1)) in your main thread loop to let some cpu to the system thread so it can propagate your button event

a sample :


volatile boolean running=false;
volatile Thread t=null;

public void start()
{
 if(t==null)
 {
  t=new Thread(this)
  running=true;
  t.start();
 }
}

public void stop()
{
 running=false;
 while(t!=null)
  Thread.sleep(100);
}

public void run()
{
 while(running)
 {
  //do something 
  Thread.yield();
 }
 t=null;
}

http://www.javamex.com/tutorials/synchronization_volatile_typical_use.shtml