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



我试图在java程序中创建多个线程,并让它们对作为命令行参数传递的整数执行算术运算。显然,我试图传递的线程类都不在主方法中,所以我怎么还能从这些类中访问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]);
}
}

您应该在构造函数中传递必要的信息

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

然后,您可以在main中将args值传递给线程,这样您就可以在可运行文件/线程中获得它们

公共类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();
}

}

最新更新