package waitNotify;
class Badminton { // 在羽球類別中,設定羽毛球物件的屬性和方法
private boolean isShooting = false;
public synchronized void sShuttlecock(int tNo) {
while (isShooting) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("射出第"+tNo+" 顆羽球");
isShooting = true;
notify();
}
public synchronized void hShuttlecock(int aNo) {
while (!isShooting) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("擊回第"+aNo+" 顆羽球");
isShooting = false;
notify();
}
}
class Shooting implements Runnable{
Badminton shuttlecock;
Shooting (Badminton shuttlecock){
this.shuttlecock = shuttlecock;
}
public void run() {
for (int i = 1; i <= 5; i++) {
shuttlecock.sShuttlecock(i);
}
}
}
class Hit implements Runnable{
Badminton shuttlecock;
Hit (Badminton shuttlecock){
this.shuttlecock = shuttlecock;
}
public void run() {
for (int i = 1; i <= 5; i++) {
shuttlecock.hShuttlecock(i);
}
}
}
public class WaitNotify {
public static void main(String[] args) {
// TODO Auto-generated method stub
Badminton shuttlecock = new Badminton();
Thread machine = new Thread(new Shooting(shuttlecock));
Thread hitter = new Thread(new Hit(shuttlecock));
machine.start();
hitter.start();
}
}