簡體   English   中英

Java:線程間共享和更改dto

[英]Java: share and change dto between threads

我有一個 dto,每 10 秒使用 1 個單獨的線程。 以前的樣子:

class BetDto {
   private String id;
   private Integer startingValue; // 10 dollars
   private Integer currentValue;  // 10 -> 8-> 9 -> 11
}

這個 dto 只是一個例子。 每隔 5 秒,這個分離的線程就會得到它,並且可以增加或減少 currentValue 的值。

目前,我將此 dto 存儲在 ConcurentHashMap 中,它是否具有安全並發性? 我想,我應該將startingValue 和currentValue 存儲為AtomicInteger。 完全正確嗎?

因為,在多線程中的所有 dto 示例中,都是具有最終字段的 dto,並且在構造函數中初始化,沒有設置器。

您應該將字段從 Integer 更改為 AtomicInteger。

即使您使用ConcurrentHashMap ,您也會看到不規則的結果。 嘗試多次運行以下代碼並查看結果。

public static void main(String[] args) throws InterruptedException {
    Map<String, BetDto> concurrentMap = new ConcurrentHashMap<>();
    concurrentMap.put("1", new BetDto("1", 1, 1));
    concurrentMap.put("2", new BetDto("2", 1, 1));

    Runnable runnable1 = () -> {
        BetDto betDto = concurrentMap.get("1");

        for (int i= 0; i < 5_00_000;i++) {
           betDto.setStartingValue(betDto.getStartingValue() + 1);
        }
    };

    Runnable runnable2 = () -> {
        BetDto betDto = concurrentMap.get("1");

        for (int i= 0; i < 5_00_000;i++) {
           betDto.setStartingValue(betDto.getStartingValue() + 1);
        }
    };

    Thread thread1 = new Thread(runnable1);
    Thread thread2 = new Thread(runnable2);
    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    System.out.println(concurrentMap.get("1").getStartingValue().toString());
}

現在將字段更改為 AtomicInteger 並運行它。 你會看到一致的結果。

class BetDto {
    private String id;
    private AtomicInteger startingValue; // 10 dollars
    private Integer currentValue;  // 10 -> 8-> 9 -> 11

    public BetDto(String id, Integer startingValue, Integer currentValue) {
        this.id = id;
        this.startingValue = new AtomicInteger(startingValue);
        this.currentValue = currentValue;
    }
    
    public AtomicInteger getStartingValue() {
        return startingValue;
    }
}

使用以下代碼從上面的代碼段更改for循環:

for (int i= 0; i < 5_00_000;i++) {
     betDto.getStartingValue().getAndAdd(1);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM