跨多个线程的可变静态变量

发布于 2024-12-26 23:41:32 字数 422 浏览 1 评论 0原文

我现在正在学习 Java 中的线程以及所有概念和关键字。我刚刚学习了 volatile 关键字,它在我的脑海中为我正在从事的项目提出了一些有趣的问题。假设我有一个名为 Connector 的类,其中包含如下字段:

    public static String DEFAULT_CONNECTION_TYPE = "UDP";

假设我将在多个线程上创建大量 Connector 对象,但每个线程将使用不同的连接方法(如“TCP”)。在将使用其他连接类型的线程上,如果我不想为每个对象显式声明它,是否有办法更改每个线程上的 DEFAULT_CONNECTION_TYPE ?是否有一个关键字可以使变量成为线程本地变量,但在该线程中仍然是静态的?这还有道理吗?

I'm learning about threads in Java right now, along with all the concepts and keywords. I just learned the volatile keyword, and it raised some interesting questions in my mind for a project I'm working on. Say I have a class called Connector with a field like this:

    public static String DEFAULT_CONNECTION_TYPE = "UDP";

Say I'll be making lots of Connector objects on multiple threads, but each thread will be using different connection methods (like "TCP"). On the threads that will be using other connection types, if I don't want to explicitly declare it for every object, is there a way to change the DEFAULT_CONNECTION_TYPE on each thread? Is there a keyword that will make a variable thread-local, yet still static across that thread? Does that even make sense?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北城孤痞 2025-01-02 23:41:32

我不建议从多个线程更改静态变量只是为了避免在类实例中携带它,但如果这就是您想要做的,请参阅 ThreadLocal

正确的方法是将连接类型设置为实例字段:

enum ConnectionType { UDP, TCP; }

class Connector {

    private static final ConnectionType DEFAULT_CONNECTION_TYPE = 
        ConnectionType.UDP;

    private final ConnectionType connectionType;

    public Connector(ConnectionType connectionType) {
        this.connectionType = connectionType;
    }

    public Connector() {
        this(DEFAULT_CONNECTION_TYPE);
    }
}

I do not recommend changing a static variable from multiple threads just to avoid carrying it in the class instance, but if that's what you want to do, see ThreadLocal.

The right way to do this is to make the connection type an instance field:

enum ConnectionType { UDP, TCP; }

class Connector {

    private static final ConnectionType DEFAULT_CONNECTION_TYPE = 
        ConnectionType.UDP;

    private final ConnectionType connectionType;

    public Connector(ConnectionType connectionType) {
        this.connectionType = connectionType;
    }

    public Connector() {
        this(DEFAULT_CONNECTION_TYPE);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文