多个线程将对象引用传递给静态帮助器方法 [英] Multiple Threads passing an object reference to static helper method

查看:56
本文介绍了多个线程将对象引用传递给静态帮助器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am just a beginner in Java and have stumbled upon multi-threaded applications. I know this question is similar to some posts here but I couldn't find a better answer for my query. Basically, I want to pass an object to a static method and the method will just return an output based on the values/properties of the object. For every call, I am creating a new instance of the object and there is no chance in any way that I will modify the object inside the method. Now, my question is, will JVM create a new instance of the static method and its local variables into the Stack (excluding the object as it will be on the Heap) for every call by multiple threads? For a clear view of what I want to achieve, here is my code:

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;
    }
}

输出:

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

Since I didn't put a synchronized keyword, the output will be different every time and it looks similar to the following: (output is correct and it is exactly what I am expecting, I just want to clarify that I am on the right path since I don't want to use synchronization as it will slow down the process because each thread will have to wait for the other thread to finish before it can call the static method)

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

推荐答案

static方法不是问题,只有static变量将在线程之间共享.

static methods are not a problem, only static variables will be shared across threads.

所以有两个线程在调用

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值.

Will fail multi-threaded, because one thread may overwrite anothers tmp value.

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

Local variables, even in static methods, are still local and thus safe.

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

Using static methods is good. It highlights that the method does not require access to object variables. Using static non-constant variables is prone to errors, avoid this at all costs (and use synchronization on a constant if you need to access the variable).

这篇关于多个线程将对象引用传递给静态帮助器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆