[英]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由于任何原因关闭,会丢失数据?
如果某些 static class 关闭,则可能是您的应用程序发生了一些严重错误。JVM 必须退出。
在多线程环境下,这种方式会造成脏读,带来一些奇怪的东西。
你可以试试下面的代码。 看看发生了什么。
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.