【问题标题】:Using for-loop inside thread won't match similar while-loop behavior在线程内使用 for-loop 不会匹配类似的 while-loop 行为
【发布时间】:2017-06-11 06:15:33
【问题描述】:

我刚开始在 Java 中使用线程,但在线程内使用 for 循环时遇到问题。

当我在线程中使用 for 循环时,由于某种原因,我看不到要发送到屏幕的输出。

当我使用 while 循环时,它就像一个魅力。

非工作代码如下:

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

调用代码:

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

我的问题是:为什么当我用 while 循环替换 for 循环并尝试将相同的输出打印到屏幕上时它不起作用?

我尝试调试它,但似乎程序在到达打印的部分之前停止了(没有异常或错误)。

【问题讨论】:

    标签: java multithreading for-loop while-loop


    【解决方案1】:
     for (int i = 1; i == 10 ; i++) {
            System.out.println(i);
        }
    

    你的意思是?

    i <= 10
    

    i == 10 是 1 == 10。它总是假的。

    【讨论】:

      【解决方案2】:

      你的 for 循环中有一个愚蠢的错字

      for (int i = 1; i == 10 ; i++) {
          ...
      }
      

      应该读作:

      for (int i = 1; i <= 10 ; i++) {
          ...
      }
      

      【讨论】:

        【解决方案3】:

        典型 for 循环在 Java 中如下所示:

           //pseudo code
            for( variable ; condition ; increment or decrement){
               //code to be executed...
            }
        

        它是如何工作的:

        1. 首先声明您的variable(也可以在循环外声明)
        2. 然后检查你的condition,如果是true,则执行循环里面的代码,否则第一次失败连循环都进不去。
        3. 然后你的increment or decrement 完成了,然后步骤2 再次发生...... 如此反复,直到conditionfalse,然后循环退出。

        在您的情况下,您的 conditioni == 10,这当然会在第一次检查时失败,因为 i 仍然是 1 并且尚未更改,因此 for 循环内的代码不是即使执行了,也根本没有进入循环。

        解决此问题:您需要将condition 更改为i &lt;= 10。通过这样做,您告诉循环“只要i 小于或等于 10,就继续循环。”

        【讨论】:

          猜你喜欢
          • 2021-05-08
          • 2014-09-14
          • 2014-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-29
          • 2019-10-06
          • 1970-01-01
          相关资源
          最近更新 更多