What is the probable output of the following code?
enum Direction{Up,Down} public class Main extends Thread { String name;//from ww w. j a v a 2 s . co m public Main(String name) {this.name = name;} public void run() { for (Direction season : Direction.values()) System.out.print(name + "-" + season + " "); } public static void main(String args[]) { Main oak = new Main("Oak"); oak.start(); Main maple = new Main("Maple"); maple.start(); } }
a, d, e, f
Each thread instance oak and maple, when started, will output the values of enum Direction-that is, Up and Down (always in this order).
The order of the elements returned by Direction.values()
isn't random.
The enum values are always returned in the order in which they are defined.
You can't guarantee whether thread oak completes or begins its execution before or after thread maple.
The thread scheduler can start oak, make it print Oak-Up, run maple so that it prints Maple-Up, return the control to oak, or run maple to completion.
Whatever the sequence, the happens-before contract guarantees that code in a thread executes in the order it's defined.
So the thread oak or maple can never print the enum value Down before the enum value Up.