将命令行参数传递给多个Java线程

问题描述 投票:0回答:1

我正在尝试在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个回答
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(); }

}

© www.soinside.com 2019 - 2024. All rights reserved.