【问题标题】:Different threads calling the method at the same time不同线程同时调用方法
【发布时间】:2013-11-09 13:04:42
【问题描述】:

我有下面的 java 程序来添加两个数字..但我试图通过线程进行开发..我在看一开始应该有五个不同的线程 命名为 T1,T2,T3,T4,T5 并且所有五个线程都应该同时调用 add 方法,请教我如何实现这五个线程应该同时调用 add 方法,以便性能可以改进..

有人可以告诉我如何通过执行器框架或 contdown 闩锁来实现这一点

public class CollectionTest {

    public static void main(String args[]) {

        //create Scanner instance to get input from User
        Scanner scanner = new Scanner(System.in);

        System.err.println("Please enter first number to add : ");
        int number = scanner.nextInt();

        System.out.println("Enter second number to add :");
        int num = scanner.nextInt();

        //adding two numbers in Java by calling method
       int result = add(number, num);

       System.out.printf(" Addition of numbers %d and %d is %d %n", number, num, result);
    }

    public static int add(int number, int num){
        return number + num;
    }
} 

【问题讨论】:

  • 你想看看当多个线程 bang 一个方法时会发生什么??

标签: java multithreading performance


【解决方案1】:

您的所有线程都可以同时调用 add 而不会产生任何后果。

这是因为在方法内部,number 和 num 变量仅对该方法是本地的 - 对调用者线程也是如此。如果 number 和/或 num 是全局的,那将是另一回事。

编辑:

例如,在这种情况下:

public static int add(int number, int num){
    //A
    return number + num;
}

当一个线程到达 A 点时,它有两个数字被传入。

当不同的线程到达 A 点时,它会调用自己的方法版本,并使用传入的不同编号。这意味着它们对第一个线程正在执行的操作没有影响。

这些数字仅适用于该方法。

在这种情况下:

static int number;

public static int add(int num){
    //A
    return number + num;
}

当一个线程到达 A 点时,它传入了 num,并且它具有外部编号,因为外部编号可供所有人访问。如果另一个线程进入该方法,它将有自己的编号(因为它调用了自己的方法版本),但它将使用相同的外部编号,因为该编号是全局的并且可供所有人访问。

在这种情况下,您需要添加特殊代码以确保您的线程正常运行。

【讨论】:

  • 能否请您展示有助于掌握的示例..!!提前致谢。
【解决方案2】:

你可以这样想 当不同线程调用 CollectionTest 的静态方法时添加

然后会发生什么: 例如:

public class Test {
/**
 * @param args
 */
public static void main(String[] args) {
    Runnable t1 = new Runnable() {
        public void run() {
            CollectionTest.add(1, 2);
        }
    };

    Runnable t2 = new Runnable() {
        public void run() {
            CollectionTest.add(3, 4);

        }
    };


    new Thread(t1).start();
    new Thread(t2).start();

}
}


public static int add(int number, int num){
    // when different thread call method 
    // for example   
    //  Runnable t1 call ,then "number" will be assigned 1, "num" will be assigned 2
    //  number ,num will keep in thread'stack spack
    return number + num;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 2013-08-30
    • 1970-01-01
    相关资源
    最近更新 更多