一旦变量设置为false,如何停止线程?

时间:2015-04-18 16:10:21

标签: java multithreading synchronization boolean

一旦我的布尔变量设置为false,如何阻止所有线程执行?例如,这是一个简单的代码: -

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();
      }
   }
}

我想只打印“1”,但是当我执行此代码时,我会得到多个数字。我该如何防止这种情况?

1 个答案:

答案 0 :(得分:1)

你不能在Java中这样做,因为Java没有像C#这样的属性。 java中最好的解决方案是:

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

但是,如果您仍希望以您想要的方式实现,那么有更糟糕的方法:

创建一个新线程,然后运行以下代码:

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

但请记住,第二种方式不应该是你的选择。坚持第一种方法好多了