スレッドの同期

戻る
同じような処理を複数のスレッドで実行させ、全体のスループットを上げたいときに
よくこのような方法をとることがあります。

ちなみに、join()は該当のスレッドが終了するのを永久に待ちつづけます。
引数のあるものは、該当のスレッドが終了しなくても、指定した時間経過すれば処理を再開します
(ただし、join(0)はjoin()と同じように永遠に待機します)。
いずれのメソッドも、外部のスレッドよりinterruptメソッドで割り込まれた場合、InterruptedExceptionを発生して処理を終了します。


$ java MasterThread
処理を開始します
山田さん: 開始しました!
鈴木さん: 開始しました!
鈴木さん: 終了しました!
山田さん: 終了しました!
行くときは一緒です。。。


/**
$Id: Thread.html,v 1.1 2009/06/22 16:12:00 kishi Exp kishi $
@author KISHI Yasuhiro
*/
public class MasterThread implements Runnable {
    public static void main( String[] args ) {
        MasterThread master = new MasterThread();
        Thread t = new Thread( master );
        t.start();
    }

    public void run() {
        System.out.println( "処理を開始します" );
        SlaveThread st1 = new SlaveThread( "山田さん", 5000 );
        SlaveThread st2 = new SlaveThread( "鈴木さん", 3000 );
        Thread t1 = new Thread( st1 );
        Thread t2 = new Thread( st2 );

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch ( InterruptedException e ) {
            e.printStackTrace();
        }

        System.out.println( "行くときは一緒です。。。" );
    }

}

/**
$Id: Thread.html,v 1.1 2009/06/22 16:12:00 kishi Exp kishi $
@author KISHI Yasuhiro
*/
public class SlaveThread implements Runnable {
    private String name = null;
    private long sleepTime;

    public SlaveThread( String name, long sleepTime ) {
        this.name = name;
        this.sleepTime = sleepTime;
    }

    public void run() {
        System.out.println( name + ": 開始しました!" );

        try {
            Thread.sleep( sleepTime );
        } catch ( Exception e ) {
            e.printStackTrace();
        }

        System.out.println( name + ": 終了しました!" );
    }

}

戻る inserted by FC2 system