1

Have created the below class with global variable. But why my thread is not ending or become dead.

public class MTTest {
  private static boolean isRequestToStop = false;

  public static void main(String [] args) throws Exception{


    Thread T = new Thread (new Runnable(){
      public void run(){

        while(!getRequestToStop()) {
        //System.out.println(" Value is " +getRequestToStop() );
        //System.out.println("Thread");
        }
      }

    });
    T.start();
    Thread.sleep(1000);
    setRequestToStop();
    //isRequestToStop =  true;
  }
  public static void setRequestToStop(){
    System.out.println("--- setRequestToStop()--- Called");
    isRequestToStop =  true; 
  }
  public static boolean getRequestToStop(){
    return isRequestToStop;

  }
}
yshavit
  • 42,327
  • 7
  • 87
  • 124

1 Answers1

2

you need to make your boolean variable volatile

private static volatile boolean isRequestToStop = false;

The created thread has its own version of isRequestToStop which will not be read/written from main memory, volatile will force your variable to be flushed to main memory.

check the java docs for more info

https://docs.oracle.com/cd/E19683-01/806-5222/codingpractices-1/index.html

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43