亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓 AtomicInteger 在 Runnable 類中工作

如何讓 AtomicInteger 在 Runnable 類中工作

楊魅力 2023-10-27 10:47:42
我用 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他們所說:它們遞增(或遞減)并隨后返回新值。



查看完整回答
反對 回復 2023-10-27
  • 1 回答
  • 0 關注
  • 120 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號