-1

I came across code to print numbers in sequence using two threads in Java. Here's the code

public class ThreadPrint {
    public static boolean isOdd = false;

    public static void main(String[] args) throws InterruptedException {
        Runnable even = () -> {
            for (int i = 0; i <= 10;)
                if (!isOdd) {
                    System.out.println("Even thread = " + i);
                    i = i + 2;
                    isOdd = !isOdd;
                }
        };
        Runnable odd = () -> {
            for (int i = 1; i <= 10;)
                if (isOdd) {
                    System.out.println("odd thread = " + i);
                    i = i + 2;
                    isOdd = !isOdd;
                }
        };

        Thread e = new Thread(even);
        Thread o = new Thread(odd);

        e.start();
        o.start();
    }
}

My question here is if I increment i as i+=2 in the loop itself like

for(int i=0; i<10; i+=2)

I get an output as Even thread= 0 and then the program stops execution. How is this thread and lambda getting this job done in the earlier style of for loop where the incrementation is inside a condition but why not in the loop declaration line itself?

  • It's called a race condition: Try increasing from `10` to `100000`. – M A Aug 18 '20 at 17:35
  • @MAnouti even if I make it to 10000 it works fine. Why is that it behaves differently when I increment in different ways(one in loop declaration line and the other in the condition in the loop) – suhas_partha Aug 18 '20 at 17:46

1 Answers1

1

for (int i = 0; i <= 10;) will not increment the variable i, hence acting as an infinite loop. Your code is not thread-safe, there is no synchronization on the accessing of isOdd between the two threads. However, since the loop is infinite, each thread will eventually pass the if(isOdd) or if(!isOdd) five times and print the values.

When the increment is placed in the for loop, most of the if checks will fail as threads are not synchronized, while there are only five attempts for each thread.

M A
  • 71,713
  • 13
  • 134
  • 174