簡體   English   中英

Java Static class 用於保存中間變量

[英]Java Static class for saving middle variables

我創建了一個中間的 class 在里面保存了很多變量,例如:

public static class Middle{
    public static List<Student> listStudent = new ArrayList<>();
    public static String level = 1; (this example of level of a character in the game)
}

並為這些變量賦值

class A{
    Middle.listStudent = GetData();
    Middle.level++;
    
    Intent intent = new Intent(A.this, B.class);
    startActivity(intent)
}

然后在接下來的 class(或活動)中,我們將這些變量與新數據一起使用

class B{
    ShowResult(Middle.listStudent);
    ShowResult(Middle.level);
}

我使用這種方式是因為不想通過 Intent 傳輸數據。

我的問題是,我們是否可以在整個應用程序中過多地使用這種方式而不會出現任何問題,如果中間 class由於任何原因關閉,會丟失數據?

  1. 如果某些 static class 關閉,則可能是您的應用程序發生了一些嚴重錯誤。JVM 必須退出。

  2. 在多線程環境下,這種方式會造成臟讀,帶來一些奇怪的東西。

你可以試試下面的代碼。 看看發生了什么。

public static void main(String[] args) {

    // create three threads to run it
    for (int i = 0; i < 3; i++) {

        //simulate multi-threaded environment
        new Thread(() -> {
            for (int j = 0; j < 10; j++) {
                StaticData.listStudent.add(Thread.currentThread().getName() + ":" + j);
                StaticData.level++;
            }
        }).start();
    }

    //show the last result , in single thread ,result must be 30 31 ,but maybe not this in multi-threaded environment
    System.out.println("Total Result listStudent's size is :" + StaticData.listStudent.size());
    System.out.println("Total Result level is :" + StaticData.level);

}

public static class StaticData {
    public static List<String> listStudent = new ArrayList<>();
    public static Integer level = 1;
}

暫無
暫無

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

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