[英]Using for-loop inside thread won't match similar while-loop behavior
I just started to use threads in Java and I'm having issues with using for loop inside a thread. 我刚开始在Java中使用线程,但是在线程内部使用for循环时遇到了问题。
When I am using a for loop inside the thread, from some reason I cannot see the outputs that I am sending to the screen. 当我在线程内使用for循环时,由于某种原因,我看不到要发送到屏幕的输出。
When I am using the while loop it works like a charm. 当我使用while循环时,它就像一种魅力。
The non-working code is the following: 无效代码如下:
public class ActionsToPerformInThread implements Runnable {
private String string;
public ActionsToPerformInThread(String string){
this.string = string;
}
public void run() {
for (int i = 1; i == 10 ; i++) {
System.out.println(i);
}
}
}
Calling code: 调用代码:
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new ActionsToPerformInThread("Hello"));
Thread thread2 = new Thread(new ActionsToPerformInThread("World"));
thread1.start();
thread2.start();
}
}
My question is: why when I'm replacing the for-loop with while-loop and try to print the same output into the screen it does not work? 我的问题是: 为什么当我用while循环替换for循环并尝试将相同的输出打印到屏幕上时,它不起作用?
I tried to debug it but it seems like the program stopped before getting to the part that its printing (There is not exception or error). 我尝试调试它,但似乎程序在到达其打印部分之前已停止(没有异常或错误)。
for (int i = 1; i == 10 ; i++) {
System.out.println(i);
}
did you mean? 你的意思是?
i <= 10
i == 10 is 1 == 10. It is always false. i == 10是1 ==10。它总是错误的。
You have a silly typo in your for loop : 您在for循环中有一个愚蠢的错字:
for (int i = 1; i == 10 ; i++) {
...
}
should probably read as: 应该读为:
for (int i = 1; i <= 10 ; i++) {
...
}
A typical for-loop looks like this in Java : Java中典型的 for循环如下所示:
//pseudo code
for( variable ; condition ; increment or decrement){
//code to be executed...
}
How it works : 这个怎么运作 :
variable
is declared (can also be declared outside loop) variable
(也可以在循环外声明) condition
is checked, if it's true
, the code inside the loop is executed, otherwise the loop will not even be entered if it fails first time. condition
(如果为true
,则执行循环内的代码,否则,如果第一次失败,则甚至不会进入循环。 increment or decrement
is done, then step 2 happens again... this goes and on repeatedly until the condition
is false
then the loop exits. increment or decrement
操作,然后再次执行第2步...重复进行,直到condition
为false
然后循环退出。 In your case your condition
is i == 10
, this of course fails the first it's checked because i
is still 1
and has not changed yet, as a result the code inside the for-loop is not even executed, the loop is not entered at all. 在您的情况下,您的
condition
是i == 10
,这当然会在第一次检查时失败,因为i
仍为1
且尚未更改,结果for循环内的代码甚至没有执行,也没有进入循环完全没有
to fix this : You need to change your condition
to i <= 10
. 要解决此问题:您需要将
condition
更改为i <= 10
。 By doing this you are telling the loop to "continue looping for as long as i
is less than OR equals to 10." 这样,您就告诉循环“只要
i
小于或等于10,就继续循环”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.