import java.util.concurrent.*;
import java.util.*;
class Animal implements Runnable {
protected String name;
protected CountDownLatch lives;
Animal(CountDownLatch lives, String name) {
this.name = name;
this.lives = lives;
}
public void run() {
try {
System.out.println("the " + this.name + " is alive");
this.lives.await();
System.out.println("the " + this.name + " is dead");
} catch (InterruptedException e) {
System.out.println("interrupted!");
}
}
}
class Killer implements Runnable {
protected CountDownLatch lives;
Killer(CountDownLatch lives) {
this.lives = lives;
}
public void run() {
while (this.lives.getCount() > 0) {
System.out.println("kill");
this.lives.countDown();
}
}
}
class Main {
public static void main(String[] args) throws InterruptedException {
// "a cat has nine lives"
CountDownLatch lives = new CountDownLatch(9);
Thread catThread = new Thread(new Animal(lives, "cat"));
catThread.start();
Thread.sleep(100);
Thread killerThread = new Thread(new Killer(lives));
killerThread.start();
catThread.join();
killerThread.join();
}
}
To embed this program on your website, copy the following code and paste it into your website's HTML: