【问题标题】:Java Static class for saving middle variables用于保存中间变量的 Java 静态类
【发布时间】:2021-10-20 18:58:23
【问题描述】:

我创建了一个中间类,里面保存了很多变量,例如:

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);
}

我使用这种方式是因为不想通过 Intent 传输数据。

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

【问题讨论】:

  • 没有。使用单个对象将所有数据存储为全局静态数据将使您的程序非常难以维护和调试。这种技术一直流行到大约 50 年前。请不要自学以这种方式编程。
  • @DawoodibnKareem 为什么这会使程序难以维护和调试?

标签: java android android-activity


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2021-08-23
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多