12/29/2008

join

In a multi-thread program, use the join method to let other thread wait until one thread finishes.
e.g.
There are two thread named 'ta' and 'tb'.

ta.join() means 'tb' waits until 'ta' finishes.


class R_A implements Runnable {
    public void run(){
        for (int i = 0; i < 100; i++) {
            System.out.println("Thread "
                + Thread.currentThread().getName());
        }
    }
}
class R_B implements Runnable {
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Thread "
                + Thread.currentThread().getName());
        }
    }
}
public class ThreadRunnable1 {
    public static void main(String[] args) {
        R_A ra = new R_A();
        R_B rb = new R_B();
        Thread ta = new Thread(ra);
        Thread tb = new Thread(rb);
        ta.setName("A");    // Set a Thread name
        tb.setName("B");    // Set a Thread name
        ta.start();
        try {
            ta.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        tb.start();
    }
}

<Result>
After the Thread A completes its execution, the Thread B executes its procedure.