简体   繁体   中英

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.

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.

When I am using the while loop it works like a charm.

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?

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.

You have a silly typo in your for loop :

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 :

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

How it works :

  1. First your variable is declared (can also be declared outside loop)
  2. Then your 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.
  3. Then your increment or decrement is done, then step 2 happens again... this goes and on repeatedly until the condition is false then the loop exits.

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.

to fix this : You need to change your condition to 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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM