【问题标题】:Multiple Threads passing an object reference to static helper method多个线程将对象引用传递给静态辅助方法
【发布时间】:2012-05-25 17:39:51
【问题描述】:

我只是 Java 的初学者,偶然发现了多线程应用程序。我知道这个问题与这里的一些帖子相似,但我找不到更好的查询答案。基本上,我想将一个对象传递给一个静态方法,并且该方法只会根据对象的值/属性返回一个输出。对于每次调用,我都在创建对象的一个​​新实例,并且我不可能以任何方式修改方法内的对象。现在,我的问题是,JVM 是否会为多个线程的每次调用创建静态方法的新实例及其局部变量到堆栈中(不包括将在堆上的对象)?为了清楚地了解我想要实现的目标,这是我的代码:

TestConcurrent.java

import classes.Player;

public class TestConcurrent
{
    private static int method(Player player)
    {
        int y = (player.getPoints() * 10) + 1;

            try {
                    Thread.sleep(1000);
            } catch (InterruptedException e) {}

            return ++y;
    }

    public static void main(String[] args) throws Exception
    {
        // Create 100 threads
        for(int i=1;i<=100;i++)
        {
            final int j = i;
            // Create a new Thread
            new Thread()
            {
                public void run()
                {
                    // Create a new instance of the Player class
                    Player player = new Player(j,j,"FirstName" + j, "LastName" + j);
                    // Call static method() and pass a new instance of Player class
                    System.out.println("Thread " + j + ": " + TestConcurrent.method(player));
                    // Check the values of the Player class after the call to the static method()
                    System.out.println("Player" + player.getAcctId() + " : Points=" + player.getPoints() + " Name=" + player.getFirstName() + " " + player.getLastName());
                }
            }.start();
        }
    }

}

Player.java

package classes;

public class Player
{
    private int acctId, points;
    String firstName, lastName;

    public Player(int acctId, int points, String firstName, String lastName)
    {
        this.acctId = acctId;
        this.points = points;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public int getAcctId() {
        return acctId;
    }
    public void setAcctId(int acctId) {
        this.acctId = acctId;
    }
    public int getPoints() {
        return points;
    }
    public void setPoints(int points) {
        this.points = points;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

输出:

由于我没有放同步关键字,所以每次输出都会不同,看起来类似于以下:(输出是正确的,这正是我所期望的,我只是想澄清一下我在正确的路径,因为我不想使用同步,因为它会减慢进程,因为每个线程必须等待另一个线程完成才能调用静态方法)

Thread 2: 22
Player8 : Points=8 Name=FirstName8 LastName8
Thread 22: 222
Thread 26: 262
Thread 23: 232
Player23 : Points=23 Name=FirstName23 LastName23
Thread 21: 212
Player21 : Points=21 Name=FirstName21 LastName21
Thread 25: 252
Player25 : Points=25 Name=FirstName25 LastName25
Thread 20: 202
Thread 19: 192
Thread 24: 242
Player24 : Points=24 Name=FirstName24 LastName24
Player9 : Points=9 Name=FirstName9 LastName9
Thread 28: 282

【问题讨论】:

  • +1 - 第一个问题很好!欢迎使用 StackOverflow!

标签: java multithreading methods static


【解决方案1】:

JVM 是否会为多个线程的每次调用创建一个静态方法的新实例及其局部变量到堆栈中(不包括将在堆上的对象)?

是的,完全正确。

如果静态方法只引用局部变量,它自动是线程安全的。 (事实上​​,这也适用于非静态方法。)

一般来说,我会说你应该尽可能避免static。一般来说,由于静态成员在某种意义上是全局的,因此它使代码更难测试和推理。

【讨论】:

  • static 方法非常好用且合理。例如Math.minMath.PI 等常量也是如此。只避免非最终的static 变量,它们会导致各种多线程错误。
  • 感谢您的快速响应。这实际上是我想要实现的。我希望辅助方法像一个全局方法一样,任何线程都可以随时调用。我最初的设计实际上是该方法在一个普通类中,然后每个线程将创建该类的一个实例,然后调用该方法。我的实际静态方法内部有很多逻辑,每次创建它的新实例时我都会担心性能。但就像我上面演示的那样,该方法不会修改传递给它的对象。如果我继续这种方式,使用静态方法会更好吗?
  • @PopoyMakisig,这是一个很难回答的问题。我曾经写过一个游戏,其中包含一个相当核心的类Server,我不得不到处转来转去,以便在这里和那里做有用的事情。我受够了并创建了静态方法。起初它看起来像是一个很大的简化,但最后我后悔这个决定并恢复了。如果我是你,我会尝试一下,看看效果如何。如果它完成了工作,请对它感到满意,如果您最终恢复,请将其作为一个教训:-)
  • @Anony-Mousse,在大多数情况下,我倾向于同意你的观点。然而,静态方法并不是一种非常面向对象的编程方式。我可以在Math 之类的类中看到它的用途,但恕我直言,这种情况非常罕见。另一个缺点是为了测试目的而模拟出方法的问题。如果它们不是静态的,这更容易做到。
【解决方案2】:

static 方法不是问题,只有static 变量会跨线程共享。

所以两个线程调用

public static int sum(int a, int b) {
  int tmp = a + b;
  return tmp;
}

不会遇到问题。

static int tmp;

public static int sum(int a, int b) {
  tmp = a + b;
  return tmp;
}

多线程会失败,因为一个线程可能会覆盖另一个tmp 值。

局部变量,即使在static 方法中,仍然是局部的,因此是安全的。

使用static 方法很好。它强调该方法不需要访问对象变量。使用static 非常量变量容易出错,不惜一切代价避免这种情况(如果需要访问变量,请在常量上使用同步)。

【讨论】:

  • 就我的应用程序而言,我不会使用任何静态非常量变量。如果我需要定义常量,我只使用最终的静态变量。所以目前一切都很简单。当我已经非常清楚 Java 的并发特性时,我将使用同步和/或实例方法。感谢您的回复。
  • 你刚刚用这句话救了我的命:“局部变量,即使在静态方法中,仍然是局部的,因此是安全的。”我对这个答案感到惊讶。直觉上感觉是错误的,但谢天谢地,它不是!
  • 使用过编译器应该是相当明显的。局部变量存储在“堆栈”中;并且由于每个线程都必须有自己的堆栈,因此它们无法看到彼此的局部变量。事实上,它们是相对于当前堆栈指针进行寻址的——因此在同一个堆栈上也可能有多个副本。否则,递归也无法正常工作。
猜你喜欢
  • 2011-09-06
  • 1970-01-01
  • 2012-08-07
  • 2019-05-05
  • 2011-06-01
  • 2011-01-15
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多