dcsimg
Controlling a thread with buttons
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Semih_Altinay
Posted On:   Thursday, August 15, 2002 03:21 PM

I have a thread that runs perfectly fine every one second. But when I try to start or stop the thread with buttons, it doesn't work. What am I doing wrong? Here is the code: ... volatile Thread runner; ... //Start the thread public void start() { runner = new Thread(this); runner.start(); } //Stop the thread public void stop() { runner = null; System.out.println("Thread has been stopped!"); } //Run the thread once every second public void run() { Thread thisThread = Thread.currentThread(); //while(runner == thisThread) while(stopButton.isEnabled   More>>

I have a thread that runs perfectly fine every one second. But when I try to start or stop the thread with buttons, it doesn't work. What am I doing wrong? Here is the code:

			

...
volatile Thread runner;
...

//Start the thread
public void start()
{
runner = new Thread(this);
runner.start();
}

//Stop the thread
public void stop()
{
runner = null;
System.out.println("Thread has been stopped!");
}

//Run the thread once every second
public void run()
{
Thread thisThread = Thread.currentThread();

//while(runner == thisThread)
while(stopButton.isEnabled())
{
//halt the thread for 1000 ms here
try { runner.sleep(1000); }
catch(InterruptedException ie)
{ System.err.println("Thread Interrupted!"); }

//process to be repeated here
sendReq();
TP.printOutput(i, ibuf, num_regs);
GP.setAllParams(i, ibuf, num_regs);
}
}
...

public void actionPerformed(ActionEvent ae)
{
String command = ae.getActionCommand();

if(command == START)
{
start();
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
else //if the command is STOP
{
stop();
stopButton.setEnabled(false);
startButton.setEnabled(true);
}
}

   <<Less

Re: Controlling a thread with buttons

Posted By:   Andrew_York  
Posted On:   Friday, August 16, 2002 11:40 AM

I usually use a boolean to control the thread.


while (keepRunning)
{
//Do Work
}


Your stop method should set keepRunning to false. This will allow a graceful exit. I think setting runner to null just throws away your refrence (and perhaps will cause a memory leak as the thread can keep running.) You may also want to try:


public synchronized void start()
{
runner = new Thread(this);
keepRunning = true;
runner.start();
}

public sychronized void stop()
{
keepRunning = false;
runner.interrupt(); //Only if you want to wake up the thread early. i.e. Stop now instead at the end of the sleep.
System.out.println("Thread has been stopped!");
}


This is just threory. . . Hopefully it helps.

Re: Controlling a thread with buttons

Posted By:   Michael_Decker  
Posted On:   Friday, August 16, 2002 08:15 AM

I don't know, why it doesn't start, but at stopping you should only set the variable null, you should interrupt that threat...
About | Sitemap | Contact