0

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).

3 Answers 3

2
 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.

Sign up to request clarification or add additional context in comments.

Comments

2

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++) {
    ...
}

Comments

0

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."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.