[英]Passing command-line arguments to mutliple java threads
我正在嘗試在 java 程序中創建多個線程,並讓它們對作為命令行 arguments 傳遞的整數執行算術運算。 顯然,我試圖傳遞給的線程類都不是在 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]);
}
}
您應該在構造函數中傳遞必要的信息
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 中的線程,以便將它們放在您的可運行對象/線程中
公共 class 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.