Java MultiThread wait until child threads die
<p>I have following Java code:</p>

<pre><code>import java.io.*;
class Global{
public static int a = 0 ;
public static int b = 0 ;
}
public class Example{
public static void main(String args[]) {
    try {
        FileOutputStream fos = new FileOutputStream("1.dat");
        DataOutputStream dos = new DataOutputStream(fos);

        for (int i = 0; i &lt; 20000; i++) {
            dos.writeInt(i);
        }
        dos.close();

        FileOutputStream fos1 = new FileOutputStream("2.dat");
        DataOutputStream dos1 = new DataOutputStream(fos1);

        for (int i = 20000; i &lt; 40000; i++) {
            dos1.writeInt(i);
        }
        dos1.close();

        Exampless.createArray(20000); //static method call to set the static arr variable
        Exampless ex1 = new Exampless("1.dat"); //found number of matches in file
        Exampless ex2 = new Exampless("2.dat");
        Thread t1 = new Thread(ex1);
        Thread t2 = new Thread(ex2);
        t1.start();
        t1.join();
        t2.start();
        t2.join();
        System.out.println("No. of Matches: " + (Global.a + Global.b ));

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
}
}

class Exampless implements Runnable {

public static int[] arr = new int[20000];
public String _name;

public Exampless(String name) {
    this._name = name;
}

static void createArray(int z) {
    for (int i = z; i &lt; z + 20000; i++) {
        arr[i - z] = i;
    }
}

public void run() {
    try {
        int cnt = 0;
        FileInputStream fin = new FileInputStream(_name);
        DataInputStream din = new DataInputStream(fin);
        for (int i = 0; i &lt; 20000; i++) {
            int c = din.readInt();
            if (c == arr[i]) {
                cnt++;
            }
        }
        System.out.println("File name: " + _name + " No. of Matches: " + cnt);
        if(_name == "1.dat")
            Global.a = cnt ;
        else if(_name == "2.dat")
            Global.b = cnt ;
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
}

}
</code></pre>

<p>There I am trying to run Exampless classes <code>run</code> method parallely. However, I want to make main thread wait until child thread finishes, which I have done using <code>join</code>. But, it makes execution of thread one after another. Can anybody help me how to solve this ? Another point is that, I want to share a variable (named as cnt which found number of matches in files)among two threads which I have done using Global class to found total number of matches. Is there any other nice solution ?</p>
