简体   繁体   English

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

[英]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? 我的布尔变量设置为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. 我只想打印“ 1”,但是当我执行此代码时,会得到多个数字。 How do I prevent this? 我该如何预防?

You can not do that in Java, because Java does not have properties like C# does for example. 您无法在Java中做到这一点,因为Java不具有C#这样的属性。 The best solution in java is to do this: Java中最好的解决方案是这样做:

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. 坚持第一种方法会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试仅在变量已设置为false的情况下运行代码 - Trying to only run code if a variable has been set to false 一旦循环到列表中的所有记录,如何停止循环 - How to stop for loop once it has been looped to all records in a list 一旦线程被中断,如何完全停止线程? - How to completely stop a thread once it has been interrupted? 一旦达到特定的障碍,如何停止动画? - How do I stop an animation once a certain barrier has been reached? 运行多个线程并在一个线程停止后停止 - Run multiple threads and stop once one has stopped 一旦在 Java 中执行了程序,如何让 for 循环停止运行并继续执行下一个方法? - How can I get the for loop to stop to stop running and proceed to the next methid once the program has been executed in Java? 即使已将代表图像的变量分配给新图像,如何停止将图像保存在ram中 - how to stop images from being saved in ram even when the variable they are represented by has been assigned to a new image SQLite 查询 - 一旦找到特定项目,停止从数据库返回行 - SQLite query - Stop returning rows from database once a specific item has been found 如何使用已在for循环中初始化的变量? - How to use a variable that has been initialized in the for loop? 达到某个值后如何触发声音 - How to trigger a sound once after a certain value has been reached
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM