When i run the following code, the program never exits and gets stuck in the while loop which should be the expected behaviour.
public class MyClass implements Runnable {
public static final int NO_OF_THREADS = 100;
private static int count;
private static Set<Integer> set = new HashSet<>();
@Override
public void run() {
for(int i=0 ;i<10000; i++) {
set.add(count++);
}
}
public static void main(String[] args) throws Exception {
Thread[] threadArray = new Thread[NO_OF_THREADS];
for(int i=0; i<NO_OF_THREADS; i++) {
threadArray[i] = new Thread(new MyClass());
}
for(int i=0; i<NO_OF_THREADS; i++) {
threadArray[i].start();
//threadArray[i].join();
}
while(set.size()!=1000000) {}
}
}
With the join() uncommented the program always exits. Moreover, When I modified the code to print the the sequence in which the threads run, with the join in place, I observed that Thread-0 first completes its task followed by Thread-1 and so on in proper numbering sequence.
Is this expected behaviour or just one of the idiosyncrasies of the JVM scheduler?