Reputation: 173
I have 2
question regarding on Thread
, I just want to clarify something. With the below code:
public class MyThread implements Runnable {
Boolean StopThread = false;
Boolean DontLoop = false;
public MyThread(){}
public void Stop(Boolean stopThread){
this.StopThread = stopThread;
}
public void ThreadDontLoop(Boolean dontLoop){
this.DontLoop = dontLoop;
}
public void run(){
if(dontLoop){
while(true){
if(StopThread){
break; //Terminate WhileLoop, This will Stop and destroy the Thread also
}
}
}else{
//Does this mean the Thread will be destroy/terminate after this condition?
}
}
}
In order to Start:
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
In order to Start Thread but Don't Loop
ThreadDontLoop(false);
thread.start();
In order to Stop the Thread
myThread.Stop(true);
Now, According to this LINK, that's how the thread to be stopped.
So my first question is, in the Given code above, what if I call ThreadDontLoop(false);
then thread.start();
, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?
Second question is, Let's say I call thread.start();
then later I call myThread.Stop(true);
to stop the WhileLoop and Destroy the Thread.
I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?
Upvotes: 0
Views: 134
Reputation: 533442
You need a volatile boolean
or the value can be inlined and never appear to change.
in the Given code above, what if I call ThreadDontLoop(false); then thread.start();, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?
Yes.
Let's say I call thread.start(); then later I call myThread.Stop(true); to stop the WhileLoop and Destroy the Thread. I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?
If you don't have a visibility issue (does the thread see your change) it will stop. In the code you have in the question, most likely the code will be optimised to assume the thread never sees the change.
Upvotes: 1