[英]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.