next up previous
Next: 12.2 排他(mutual exclusion)制御 Up: 12 同期処理 Previous: 12 同期処理

12.1 スレッドの終了待ち join


// join.java
class CustomThread2 extends Thread
{
    CustomThread2(String name)
    {
        super(name);
        start();
    }

    public void run()
    {
        try {
            for(int loop_index = 0;
                loop_index < 4;
                loop_index++) {
                System.out.println(
                    (Thread.currentThread()).getName()
                    + " thread here...");
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {}
        
        System.out.println(
            (Thread.currentThread()).getName() + 
            " ending.");
    }
}

class join
{
    public static void main(String args[])
    {
        CustomThread2 thread1 =
            new CustomThread2("first");
        CustomThread2 thread2 =
            new CustomThread2("second");
        CustomThread2 thread3 =
            new CustomThread2("third");
        CustomThread2 thread4 =
            new CustomThread2("fourth");

        try {
            thread1.join();
            thread2.join();
            thread3.join();
            thread3.join();
        } catch (InterruptedException e) {}
    }
}
実行すると,
% java join
first thread here...
second thread here...
third thread here...
fourth thread here...
first thread here...
second thread here...
third thread here...
fourth thread here...
first thread here...
second thread here...
third thread here...
fourth thread here...
first thread here...
second thread here...
third thread here...
fourth thread here...
first ending.
second ending.
third ending.
fourth ending.
となる.

generated through LaTeX2HTML. M.Inaba 平成18年5月7日