[Java]マルチスレッドでの、子スレッド終了待ち処理サンプル


基礎からわかるTCP/IP Javaネットワークプログラミング


package com.nanoappli.test
 
// マルチスレッド処理サンプル
public class MultiThreadSample {
    public static void main( String args[] ) {
        TestClass inClass = ( new MultiThreadSample() ).getTestClass();
 
        /*------------------------*/
        /* 子スレッドの実行を行う */
        /*------------------------*/
        System.out.println( "test1" );
        Thread childThread = new Thread( inClass );
        childThread.start();
        System.out.println( "test2" );
 
 
        /*------------------------*/
        /* 親スレッドの仕事を行う */
        /*------------------------*/
        System.out.println( "main : start" );
        try {
            for ( int loop = 0; loop < 3; loop++ ) {
                System.out.println( "parent:" + String.valueOf( loop ) );
                java.lang.Thread.sleep( 1000 );
            }
        } catch ( InterruptedException ex ) {
            ex.printStackTrace();
        }
 
 
        /*----------------------------*/
        /* 子スレッドが終わるまで待つ */
        /*----------------------------*/
        try {
            synchronized ( childThread ) {
                childThread.wait();
            }
        } catch ( InterruptedException ex ) {
            ex.printStackTrace();
        }
 
        /* PG終了 */
        System.out.println( "main : end" );
    }
 
 
    //-------------------------------------------------------------------
    // インナークラスの取得メソッド
    //-------------------------------------------------------------------
    TestClass getTestClass() {
        return new TestClass();
    }
 
 
    //-------------------------------------------------------------------
    // 別スレッドで起動する内部クラス
    //-------------------------------------------------------------------
    class TestClass implements Runnable
    {
 
        // 子スレッド処理(Thread.start()からコールされる)
        public void run() {
            try {
                for ( int loop = 0; loop < 5; loop++ ) {
                    System.out.println( "child:" + String.valueOf( loop ) );
                    java.lang.Thread.sleep( 1000 );
                }
                System.out.println( "child:end" );
            } catch ( InterruptedException ex ) {
                ex.printStackTrace();
            }
 
            // 自分待ちになっているオブジェクトがいたら起こしてあげる
            synchronized ( this ) {
                this.notifyAll();
            }
        }
    }
}



TCP/IPソケットプログラミング Java編

関連記事

コメントを残す

メールアドレスが公開されることはありません。