我正在尝试创建一个新的线程进程,线程进程结束后我想从该类中获取结果。我该怎么做?
比如这两个类。假设 abThread 类返回 String 数组。我应该如何获得这些字符串值。
Class A{
public static void main(String[] args){
abThread bb=new abThread();
bb.start();
// when bb.run() returns data catch it
}
}
Class abThread extends Thread{
public void run(){
**// do smth here**
// then return result to the main Class
}
}
最佳答案
您正在寻找的是像这样的 Callable:
public class MyCallable implements Callable<String[]>
{
@Override
public String [] call() throws Exception
{
//Do your work
return new String[42]; //Return your data
}
}
public static void main(String [] args) throws InterruptedException, ExecutionException
{
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<String[]> future = pool.submit(new MyCallable());
String[] myResultArray = future.get();
}
关于Java 在两个类之间传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36036489/