public class ThreadStateVerifier {
public static void main(String[] args) {
// TODO Auto-generated method stub
VerifyThread t = new VerifyThread() ;
Thread th = new Thread(t) ;
th.start() ;
for(int i = 0 ; i < 5 ; i++){
if(i == 4)
{
t.setactive(false) ;
}
}
}
}
class VerifyThread implements Runnable{
private String message = "It is working" ;
private volatile boolean active = true ;
private static int i = 0 ;
public void run(){
try{
for( ; active ; i++){
System.out.println("i is" + i);
Thread.sleep(1000) ;
}
}
catch(InterruptedException ie){}
}
public static void setactive(boolean active){
active = active ;
}
}
I want to set the value of active to false, when the thread is actually running.
When I run this program, VerifyThread goes into an infinite loop, i.e. active is not set to false, although its value is set to false by main explicitly.
If my approach is wrong then please suggest the right approach to do it. The objective is that the value of active should be set to false, so that the VerifyThread stops sometime later on.
I don’t want to use any intermediary queue which stores the value of active as it will be an overhead on memory.
When you are calling this method:
you are doing a redundant assignment from the parameter variable to itself. To reference the class member you need:
Edit: Looking over the code, I can see that what you are trying to do will not work anyway. You are starting a thread in parallel and then immediately telling it to stop (executing 5 iterations of loop is negligible). You will probably not see any output on the console.
If you could tell us what exactly it is that you want to do, maybe we can help you redesign this.