Java Thread behaving synchronously

47 Views Asked by At

in the below piece of code when ever the while loop is empty it's going in an infinite loop as the flag updated by thread 2 isn't getting reflected

public class testing2 {
    private static boolean flag = false;

    public static void main(String[] args) {
        // Thread 1: Toggles the flag value
        Thread thread1 = new Thread(() -> {
            while (!flag) {
                //System.out.println("hello");
            }
            System.out.println("Flag is now true!");
        });

        // Thread 2: Changes the flag value after a delay
        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(1000); // Delay for 1 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true;
            System.out.println("Flag has been set to true.");
        });

        // Start both threads
        thread1.start();
        thread2.start();
    }
}

result : "Flag has been set to true." and continues running

but whenever i uncomment the code in while loop i'm getting below response

. . . Hello hello hello Flag has been set to true. Flag is now true!

Kindly help me understand why is it behaving like this

i was trying to reproduce an error scenario

0

There are 0 best solutions below