简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM