我用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
类。
发布于 2019-10-14 23:05:28
我假设您的教授希望您将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();
}
正如decrementAndGet
和incrementAndGet
所做的那样:它们会递增(或递减),然后返回新值。有关更多信息,请查看the Javadoc。
干杯!
https://stackoverflow.com/questions/58384928
复制