Java在两个类之间传递值

时间:2016-03-16 13:02:24

标签: java multithreading class

我正在尝试创建一个新的线程进程,在线程进程结束后我想从该类获得结果。我能做到吗?
例如这两个类。让我们说abThread类返回String数组。我该如何获得这些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
    }
}

1 个答案:

答案 0 :(得分:3)

你正在寻找的是像这样的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();
    }