38. スレッドの通信

38. スレッドの通信

スレッドを一時的に待機

L:\lesson095\test.java

class test extends Thread {
    static Neko neko;
    public static void main(String args[]) {
        neko = new Neko();
        new test().start();
        new test().start();
    }
    public void run() {
        neko.tell();
    }
}

class Neko {
    int ch = 0;
    synchronized void tell() {
        if (ch < 1) {
            try {
                ch++;
                System.out.println("Kitty on your lap");
                Thread.sleep(1000);
                wait(3000);
                System.out.println("おはようございますご主人様");
            }
            catch (InterruptedException err) {
                System.out.println(err);
            }
        }
        else {
            System.out.println("ひざの上の同居人");
        }
    }
}

実行結果

L:\lesson095>java test
Kitty on your lap
ひざの上の同居人
おはようございますご主人様

待機しているスレッドの呼び出し

L:\lesson096\test.java

class test extends Thread {
    static Neko neko;
    public static void main(String args[]) {
        neko = new Neko();
        new test().start();
        new test().start();
    }
    public void run() {
        neko.tell();
    }
}

class Neko {
    int ch = 0;
    synchronized void tell() {
        if (ch == 0) {
            try {
                ch++;
                System.out.println("wait() メソッドで停止します");
                Thread.sleep(1000);
                wait();
                Thread.sleep(1000);
                System.out.println("待機状態を解除しました");
            }
            catch (InterruptedException err) {
                System.out.println(err);
            }
        }
        else {
            System.out.println("待機を解除します");
            notify();
        }
    }
}

実行結果

L:\lesson096>java test
wait() メソッドで停止します
待機を解除します
待機状態を解除しました

待機状態を全て解除

L:\lesson097\test.java

class test extends Thread {
    static Neko neko;
    public static void main(String args[]) {
        neko = new Neko();
        for(int i = 0 ; i < 5 ; i++)
            new test().start();

        new test().start();
    }
    public void run() {
        neko.tell();
    }
}

class Neko {
    int ch = 0;
    synchronized void tell() {
        if (ch < 4) {
            try {
                ch++;
                System.out.println("wait() メソッドで停止します");
                Thread.sleep(1000);
                wait();
                Thread.sleep(1000);
                System.out.println("待機状態を解除しました");
            }
            catch (InterruptedException err) {
                System.out.println(err);
            }
        }
        else {
            System.out.println("待機を全て解除します");
            notifyAll();
        }
    }
}

実行結果

L:\lesson097>java test
wait() メソッドで停止します
wait() メソッドで停止します
wait() メソッドで停止します
wait() メソッドで停止します
待機を全て解除します
待機を全て解除します
待機状態を解除しました
待機状態を解除しました
待機状態を解除しました
待機状態を解除しました