简体   繁体   English

Java Static class 用于保存中间变量

[英]Java Static class for saving middle variables

I create a middle class save many variables in it, example:我创建了一个中间的 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)
}

And assign value for those variables并为这些变量赋值

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

And then in next class (or activity) we using those variables with new data然后在接下来的 class(或活动)中,我们将这些变量与新数据一起使用

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

I using this way because don't want to transfer data by Intent.我使用这种方式是因为不想通过 Intent 传输数据。

My question is, can we using this way too much in the whole application without getting any issue, and if the middle class it shut down for any reason, makes losing data?我的问题是,我们是否可以在整个应用程序中过多地使用这种方式而不会出现任何问题,如果中间 class由于任何原因关闭,会丢失数据?

  1. If some static class become shutdown, maybe some serious error occurs in your application.The JVM had to exit.如果某些 static class 关闭,则可能是您的应用程序发生了一些严重错误。JVM 必须退出。

  2. In multithreading environment,this way can cause dirty read and brings into some strange thing.在多线程环境下,这种方式会造成脏读,带来一些奇怪的东西。

You can try the code below.你可以试试下面的代码。 And see what's going on.看看发生了什么。

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