【问题标题】:Passing command-line arguments to mutliple java threads将命令行参数传递给多个 java 线程
【发布时间】:2019-11-13 19:53:46
【问题描述】:

我正在尝试在 java 程序中创建多个线程,并让它们对作为命令行参数传递的整数执行算术运算。显然,我试图传递给的线程类都不是在 main 方法中,所以我怎样才能从这些类中访问像 args[0] 这样的变量?

public class Mythread {

    public static void main(String[] args) {
        Runnable r = new multiplication();
        Thread t = new Thread(r);
        Runnable r2 = new summation();
        Thread t2 = new Thread(r2);
        t.start();
        t2.start();
    }
}

class summation implements Runnable{
    public void run(){
        System.out.print(args[0]);
    }
}

class multiplication implements Runnable{
    public void run(){
        System.out.print(args[1]);
    }
}

【问题讨论】:

    标签: java multithreading parameter-passing


    【解决方案1】:

    你应该在构造函数中传入必要的信息

    class Summation implements Runnable {
    
        private final String info;
    
        public Summation(String info) {
          this.info = info;
        }
    
        @Override
        public void run(){
            System.out.print(info);
        }
    }
    

    然后您可以将 args 值传递给 main 中的线程,以便将它们放在您的可运行对象/线程中

    公共类 Mythread {

    public static void main(String[] args) {
        Runnable r = new multiplication(args[1]);
        Thread t = new Thread(r);
        Runnable r2 = new summation(args[0]);
        Thread t2 = new Thread(r2);
        t.start();
        t2.start();
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 2015-06-09
      • 2017-10-22
      相关资源
      最近更新 更多