public class TrainTraffic {
public static void main(String[] args) {
Cave cave = new Cave();
Car car1 = new Car(cave, "马车", 1000);
Car car2 = new Car(cave, "汽车", 3000);
Car car3 = new Car(cave, "火车", 5000);
car1.start();
car2.start();
car3.start();
}
}
//山洞类
class Cave {
//汽车通过方法
public synchronized void crossCar(Car car) {
try {
System.out.println(car.name + "in....");
Thread.sleep(car.time);
System.out.println(car.name + "out....");
} catch (Exception e) {
}
}
}
class Car extends Thread {
public int time;
public String name;
public Cave cave;
public Car(Cave cave, String name, int time) {
this.name = name;
this.time = time;
this.cave = cave;
}
public void run() { // 在 run 方法中 运行 同步代码块/(静态)同步方法。 在同步代码块/(静态)同步方法中,对要需要保证同步的资源进行修改。保证互斥性。
cave.crossCar(this);
}
}