日期:2014-05-20 浏览次数:20876 次
package rabitmq01.test02;
import java.util.concurrent.CountDownLatch;
public class BirdFish {
public static void main(String[] args) throws InterruptedException {
Pond pond = new Pond() ;
pond.birdCount = 5 ;
pond.fishCount = 20 ;
BirdThread bt = new BirdThread(pond) ;
FishThread ft = new FishThread(pond) ;
bt.start();
ft.start();
Thread.sleep(100); //等上面两个线程先执行
while(pond.fishCount > 0){
synchronized (pond) {
pond.time += 10 ;
pond.countDown = new CountDownLatch(2);
pond.notifyAll();
}
pond.countDown.await();
}
System.exit(-1);
}
}
class Pond{
int birdCount ;
int fishCount ;
long time ;
CountDownLatch countDown ;
public void printInfo(){
System.out.printf("time[%d]:bird[%d],fish[%d]\n" , time , birdCount , fishCount);
}
}
class BirdThread extends Thread{
Pond pond ;
public BirdThread(Pond pond){
this.pond = pond ;
}
@Override
public void run() {
while(pond.fishCount > 0){
synchronized (pond) {
try {
pond.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(pond.time % 10 ==0){
if(pond.fishCount >= pond.birdCount)
pond.fishCount -= pond.birdCount ;
else{
pond.fishCount = 0 ;
}
if(pond.time % 60 == 0){
pond.birdCount += pond.birdCount ;
}
pond.printInfo();
}
}
pond.countDown.countDown();
}
}
}
class FishThread extends Thread{
Pond pond ;
public FishThread(Pond pond){
this.pond = pond ;
}
@Override
public void run() {
while(pond.fishCount > 0){
synchronized (pond) {
try {
pond.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(pond.time % 30 == 0){
pond.fishCount += pond.fishCount * 2 ;
pond.printInfo();
}
}
pond.countDown.countDown();
}
}
}