1. 無限ループ内に1,2,3,...を出力させ、このループを特定のキー入力で止める。

以前, 作ったものですが, Thread を使ってみました.

前回のはこちら.
1. 無限ループ内に1,2,3,...を出力させ、このループを特定のキー入力で止める。 - Think Different - はてな版

/**
 * $Id: Example1.java 1632 2007-08-17 12:59:37Z nanasess $
 */
package jp.examples;

import java.io.IOException;

/**
 * Example1
 *
 * <pre>
 * 1. Display series of numbers (1,2,3,4, 5....etc) in an infinite loop.
 *    The program should quit if someone hits a specific key (Say ESCAPE key).
 * </pre>
 *
 * @author $Author: nanasess $
 * @version $Revision: 1632 $ $Date: 2007-08-17 21:59:37 +0900 (金, 17 8 2007) $
 */
public class Example1 {

    /** キーの入力コード */
    static int c;

    /**
     * 任意のキーを押すまで, 無限ループさせループ数を出力する.
     *
     * @throws IOException 入力例外が発生した場合
     * @see http://d.hatena.ne.jp/kajidai/20061025/1161711473
     * @see http://forums.programming-designs.com/viewtopic.php?pid=3482
     */
    public static void main(String[] args) throws IOException {

        Loops loops = new Loops();
        Input input = new Input();

        Thread thread1 = new Thread(loops);
        Thread thread2 = new Thread(input);

        thread1.start();
        thread2.start();
    }

    /**
     * キーの入力を受け付け, キーコードを出力する.
     */
    static class Input implements Runnable {

        public void run() {
            try {
                c = System.in.read();
                System.out.println(c);
            } catch (IOException e) {
            }
        }
    }

    /**
     * キーの入力があるまで数値を加算しながら無限ループする.
     */
    static class Loops implements Runnable {

        public void run() {
            int i = 0;
            while (true) {
                System.out.println(i);
                if (c != 0) {
                    System.out.println("STOP!");
                    break;
                }
                i++;
            }
        }
    }
}