Home > OS >  Java Race condition
Java Race condition

Time:06-12

In the code snippet here under, "Mares do not eat oats." is not getting printed. It is expected that after completing sleep of 2000ms, it will run that print statement, but it is never reaching there.

public class BadThreads {
    
        static String message;
    
        private static class CorrectorThread
            extends Thread {
    
            public void run() {
                try {
                    sleep(1000); 
                } catch (InterruptedException e) {}
                // Key statement 1:
                message = "Mares do eat oats."; 
            }
        }
    
        public static void main(String args[])
            throws InterruptedException {
    
            (new CorrectorThread()).start();
            message = **"Mares do not eat oats.**";
            Thread.sleep(2000);
            // Key statement 2:
            System.out.println(message);
        }
    }

CodePudding user response:

The statement you marked is being reached.

While your main-Thread sleeps, the "CorrectorThread" changes the value of message to "Mares do eat oats." and does not print the message. CorrectorThread then finished execution.

main-Thread wakes up from its sleep and prints the value of the variable message, which is now "Mares do eat oats."

Note that the variable message is shared by both threads. Maybe you are used to C's fork() statement, which would launch a new process, and would subsequently not share the memory with the main-Thread anymore.

  • Related