Saturday, April 25, 2015

Threads share static variable but behave differently with respect to it

Here is my code. Obviously this doesn't do a lot but that's only because I abstracted out the problem so that you guys didn't have so many lines to decipher.

Java Code:

import java.util.Scanner;

class threadOne extends threadTwo {
        
        public static void main(String[] args) {
                
                threadTwo threadTwoObj = new threadTwo();
                threadTwoObj.start();
                
                while (!userInput.equals("exit")) {
                        Scanner scannerObj = new Scanner(System.in);
                        userInput = scannerObj.nextLine();
                }
                
        }
        
}

Java Code:

class threadTwo implements Runnable {

        private Thread threadObj;
        public static String userInput = "default";

        public void start() {
                threadObj = new Thread (this, "Thread Two");
                threadObj.start();
        }
        
        public void run() {
                while (!userInput.equals("exit")) {}
        }
}
What its supposed to do: When the user returns "exit" in the console it is supposed to break out of both while loops in both threads.
What it actually does: breaks out of the while loop in threadOne and not in threadTwo.

In case you are wondering the idea behind this, basically the idea is to have a thread running doing computation and another thread able to query it for updates or interact to make changes to the flow. This will be useful, among other ways, for the sorts of problems where finding a solution is easy but where a better solution can always be found with more time. So for example finding directions on a map. Its easy to find a solution, but if you search longer you can find a faster route, if you search longer still than faster still.

No comments:

Post a Comment