如何让 AtomicInteger 在 Runnable 类中工作

我用 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类实现到代码中。


杨魅力
浏览 88回答 1
1回答

交互式爱情

我猜你的教授希望你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他们所说:它们递增(或递减)并随后返回新值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java