awsdfw
awsdfw

Reputation: 11

How to stop threads once variable has been set to false?

How do I stop all threads from executing further once my boolean variable has been set to false? For example, here's a simple code:-

class testing implements Runnable{
   static boolean var;
   int id;
   public void run(){
      System.out.println(id);
      var = false;
   }
   testing(int id){
      this.id = id;
   }
   public static void main(String[] args){
      int i = 1;
      var = true;
      while(var){
         new Thread(new testing(i++)).start();
      }
   }
}

I want to print only "1", but when I execute this code, I get multiple numbers. How do I prevent this?

Upvotes: 1

Views: 132

Answers (1)

Victor2748
Victor2748

Reputation: 4199

You can not do that in Java, because Java does not have properties like C# does for example. The best solution in java is to do this:

public void setMyVariable(boolean v) {
    var = v;
    // code to stop executing threads
}

However, if you still want to make it the way you want, there is a much worse way to do that:

Create a new thread, and run this code:

boolean run = true;
while(run) {
    if (!var) {
        // code to stop your threads
        run = false;
    }
}

But keep in mind, the 2nd way shouldn't really be your option. It is much better to stick with the first method.

Upvotes: 1

Related Questions