我想知道是否有任何方法可以将“void”对象传递给 Java ArrayList。
例如,我想通过引用 list1.put(doThis()); 来将 void 对象“public void doThis()”传递给数组列表;
当将对方法的引用传递给数组列表对象时,我得到以下信息:
The method add(Object) in the type ArrayList<Object> is not applicable for the arguments (void)
我正在尝试创建一个类,它可以获取对其他类中方法的引用的 ArrayList,并迭代以在线程中执行这些方法。
package asWebRest.shared;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ThreadRipper {
private int maxThreads = 4;
private int maxThreadsHost = 8;
public void runProcess(String pString) {
System.out.println(" --> Running [ "+pString+" ]");
String s = null;
String[] pArray = { "bash", "-c", pString };
try {
Process p = new ProcessBuilder(pArray).start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) { System.out.println(s); }
while ((s = stdError.readLine()) != null) { System.out.println(s); }
p.destroy();
}
catch (IOException e) { e.printStackTrace(); }
System.out.flush();
}
public String runProcesses() {
boolean pool = false;
WebCommon wc = new WebCommon();
ArrayList<Object> threadList = new ArrayList<Object>();
threadList.add(runProcess("ls -l"));
threadList.add(runProcess("ls -s"));
threadList.add(runProcess("ls -al"));
String runResults = "";
int procLoop = 0;
int inPool = 0;
for(int i = 0; i < threadList.size(); i++) {
Object exTask = threadList.get(i);
if(!pool) {
if(inPool < maxThreads) {
runResults += "Loop [" + procLoop + "] Thread [" + inPool + "]: " + exTask + "\n";
inPool++;
} else {
procLoop++;
inPool = 0;
}
} else {
runResults += "Pool Thread [" + inPool + "]: " + exTask + "\n";
inPool++;
}
}
return runResults;
}
public int getMaxThreads() { return maxThreads; }
public int getMaxThreadsHost() { return maxThreadsHost; }
}
最佳答案
您正在做的是添加 runProcess("ls -l")
的返回而不是引用runProcess
,并且自 runProcess
不返回任何内容,Java 显示无法添加的错误 void
到列表中。
您需要使用 Runnable
的列表s。
List<Runnable> processes = new ArrayList<Runnable>();
以这种方式将其添加到列表中,
processes.add(()->runProcess("ls -l"));
然后您可以使用进程列表执行您选择的任何操作,
for(Runnable process : processes) {
process.run();// You can other fancy stuff here.
new Thread(process).start(); // eg : spawn in new thread.
}
关于java - 将方法(或 void)传递给 Java ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59535431/