class CalculatePrice {
private int workArea;
private boolean available = false;
//synchronized指定。pricePutメソッドが終了するまで、
//メソッドが属するオブジェクトはアクセスされない
public synchronized void pricePut(int price) {
while (available == true) {
try {
wait(); //availableがtrueの間、wait
} catch (InterruptedException e) {
}
}
//workAreaに値をセットする処理
workArea = price;
available = true;
//availableにtrueを代入した後wait状態のスレッドを解除
notifyAll();
}
//synchronized指定。priceGetメソッドが終了するまで、
//メソッドが属するオブジェクトはアクセスされない
public synchronized void priceGet() {
while (available == false) {
try {
wait(); //availableがfalseの間、wait
} catch (InterruptedException e) {
}
}
//workAreaから値を抜出す処理
System.out.println("課税後価格は" +
workArea * 1.05 + "円です。");
available = false;
//availableにfalseを代入した後wait状態のスレッドを解除
notifyAll();
}
}
【PutPrice.javaファイル】
class PutPrice extends Thread {
private CalculatePrice cp;
private int[ ] price = {100, 200, 300, 400, 500};
//コンストラクタ内で引数に指定されたオブジェクトcpを代入
public PutPrice(CalculatePrice cp) {
this.cp = cp;
}
public void run() {
for (int i = 0; i < 5; i++) {
//オブジェクトcpのpricePutメソッドを実行
cp.pricePut(price[i]);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
【GetPrice.javaファイル】
class GetPrice extends Thread {
private CalculatePrice cp;
//コンストラクタ内で引数に指定されたオブジェクトcpを代入
public GetPrice(CalculatePrice cp) {
this.cp = cp;
}
public void run() {
for (int i = 0; i < 5; i++) {
//オブジェクトcpのpriceGetメソッドを実行
cp.priceGet();
}
}
}
【ExThread5.javaファイル】
public class ExThread5 {
public static void main(String[] args) {
CalculatePrice cp = new CalculatePrice();
//オブジェクトcpを引数にスレッドオブジェクトppの生成
PutPrice pp = new PutPrice(cp);
//オブジェクトcpを引数にスレッドオブジェクトgpの生成
GetPrice gp = new GetPrice(cp);
pp.start(); //スレッドを実行可能状態にする
gp.start(); //スレッドを実行可能状態にする
}
}