有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于保存中间变量的安卓 Java静态类

我创建了一个中产阶级,并在其中保存了许多变量,例如:

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 B{
    ShowResult(Middle.listStudent);
    ShowResult(Middle.level);
}

我之所以使用这种方式,是因为我不想故意传输数据

我的问题是,我们是否可以在整个应用程序中过多地使用这种方式而不产生任何问题,并且如果中产阶级出于任何原因关闭它,导致数据丢失


共 (1) 个答案

  1. # 1 楼答案

    1. 如果某个静态类关闭,可能会出现严重错误 在应用程序中发生。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;
    }