简体   繁体   English

从另一个类更改变量

[英]Changing a variable from another class

If I have a primary class (primary as in it has most of the code, the run method, etc) that is running and a Thread running in a different class, can the Thread change a [public static] boolean that resides in the primary class and the primary class reacts accordingly? 如果我有一个正在运行的主类(其中的主代码包含大部分代码,运行方法等),并且一个线程在其他类中运行,则该线程可以更改驻留在主类中的[public static]布尔值吗?班和小学班做出相应反应?

Please specify if I'm being unclear! 请指明我是否不清楚!

You can assign to static public members from an other class from a Thread. 您可以从Thread中的其他类分配静态公共成员。 But, think about concurrent acces. 但是,请考虑并发访问。 So you need to protect the access to this member using the Java keyword synchronized . 因此,您需要使用Java关键字synchronized来保护对此成员的访问。

The best way to do that is: 最好的方法是:

private static String thing = "dskfjksf";

public static void setThing(String newValue) {
    synchronized(thing) {
        thing = newValue;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM