JAva開発実戦経典(第2版)P 2839-1


9.1   4つのスレッドオブジェクトを設計し、2つのスレッドは減算を実行し、2つのスレッドは加算を実行します.
package book;

class MyThread implements Runnable {
	private int count = 0;

	public void run() {
		while (true) {
			if (Thread.currentThread().getName().startsWith("mul")) {
				count--;
			} else {
				count++;
			}
			System.out.println(count);
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}
}

public class JiOu {
	public static void main(String args[]) {
		MyThread mt = new MyThread();
		Thread mt1 = new Thread(mt, "mul1");
		Thread mt2 = new Thread(mt, "mul2");
		Thread mt3 = new Thread(mt, "add3");
		Thread mt4 = new Thread(mt, "add4");
		mt1.start();
		mt2.start();
		mt3.start();
		mt4.start();
	}
}

実行結果:(部分)
-1
-1
-2
0
1
1
0
1
2
3
2
2
1
2
1
2
2
2
3
1
3
2
3
3
1
1
2
3
4