我用 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类实现到代码中。
1 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
我猜你的教授希望你counter
改成AtomicInteger
. 首先,您需要导入AtomicInteger
并更改构造函数的声明counter
以反映这一点。
import java.util.concurrent.atomic.AtomicInteger;
public GarageWorker(int initialCarCount) {
counter = new AtomicInteger(initialCarCount);
}
public AtomicInteger counter;
另外,您想要更改increaseVehicleCount和decreaseVehicleCount方法以便使用AtomicInteger代替int。
public int increaseVehicleCount() {
return counter.incrementAndGet();
}
public int decreaseVehicleCount() {
return counter.decrementAndGet();
}
incrementAndGet
以及正如decrementAndGet
他们所说:它们递增(或递减)并随后返回新值。
添加回答
举报
0/150
提交
取消