I have a thread running but from outside I can\'t bypass a value to stop that thread. How can I send false/true value inside Mytest()
or call running thread pub
You should always use the interrupt method to stop a thread. This is a safe and the adequate way to perform a stop operation an a thread.
Thread tThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try{
Thread.sleep(10);
... do you stuff...
}catch(InterruptedException ex){
break;
}
}
}
});
tThread.start();
And when you would like to stop you thread just invoke the interrupt method:
tThread.interrupt();
public void run()
{
while(!isInterrupted()) {
if (onoff) {
return;
} else {
if (status==false) System.out.println("running");
}
}
}
Then use Thread.interrupt() to indicate a interrption of the thread.
Note: Don't use Thread.stop() under any circumstance! It's Deprecated!
For more detail, JDK document and << Java Concurrency in Practice >> can be referred to.
if you define it by class rather than as a Runnable
you can call the instance methods.
public static Mytest runnable;
Also note that due to multiple cores having their own associated memory, you need to warn the processor that the state may be changed on another processor and that it needs to watch for that change. Sounds complicated, but just add the 'volatile' keyword to the boolean flags
public class Mytest implements Runnable
{
private static volatile boolean running = true;
public void run()
{
while(running) {
// do stuff
}
}
public void stop() { running = false;}
}
Start the Runnable
as in your initial code, then shut it down using runnable.stop()
in your run method...
dont do while(true)..
use a boolean... like... while(threadIsRunning)
and this boolean you can set to true/false....
Apart from the fact, that this thread is a heating test for your CPU ;)
You can call the start/stop methods with
MyThread.start();
MyThread.stop();
You've defined them as static
methods, so the above lines of code show how to call them.
for the heating... add something like
try {
Thread.sleep(100); // value is milliseconds
} catch (InterruptedException e) {
// no need to handle (in this example)
}
This will reduce the CPU load from 100% (on one core) to a reasonable value ;)