Java 在两个类之间传递值

标签 java multithreading class

我正在尝试创建一个新的线程进程,线程进程结束后我想从该类中获取结果。我该怎么做?
比如这两个类。假设 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/

相关文章:

java - 从层次结构中捕获显式异常

java - 每次运行定义的循环都会给出不同的时间

java - Java 脚本引擎用在哪里?

python - 每个线程的 CPU 使用率

java - Java中如何允许多个线程同时访问一个随机访问文件

javascript - 你能在 React 组件类中添加一个外部函数作为方法吗?

java - 字符串索引错误

C# BackgroundWorker 和 ProgressBar 问题

python - 通过列表引用类实例

javascript - 是否可以在 ES2015 中导入类方法