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?