我用 Java 编写了这段代码Runnable,但我的教授希望我添加AtomicInteger,以便不存在线程干扰。我该如何去做呢?我尝试查找如何在代码中使用它的示例,但我不知道在这种情况下该怎么做。
public class GarageWorker {
public static void main(String[] args) {
System.out.println("We are going to count the vehicles in the garage");
System.out.println();
System.out.println("There are 50 vehicles in the garage to start with!");
System.out.println();
GarageWorker garage = new GarageWorker(50);
Runnable vehicleEnter = garage.new Enter();
Runnable vehicleExit = garage.new Exit();
Thread thread1 = new Thread(vehicleEnter);
Thread thread2 = new Thread(vehicleExit);
thread1.start();
thread2.start();
}
public GarageWorker(int initialCarCount) {
counter = initialCarCount;
}
public int counter;
public class Enter implements Runnable {
public Enter() {
}
public int increaseVehicleCount() {
return ++counter;
}
public void run() {
while (counter < 100) {
System.out.println("One vehicle entered the garage now there are " + increaseVehicleCount());
}
}
}
public class Exit implements Runnable {
public Exit() {
}
public int decreaseVehicleCount() {
return --counter;
}
public void run() {
while (counter > 0) {
System.out.println("One vehicle left the garage now there are " + decreaseVehicleCount());
}
}
}
}
代码运行良好,但我的教授希望我将AtomicInteger类实现到代码中。
交互式爱情
相关分类