2015-10-12 69 views
2

我的问题是,我只想从多个线程中同时运行的多个线程中返回多个值。每次调用线程并运行时,我都需要一个返回值。请证明我感谢你,我的代码片段看起来像这样,Thread1:我调用java到本地库函数,函数返回整数值。如何从多线程返回值?

public void run() { 
      double time = System.currentTimeMillis(); 
      println("Thread-1 starts " + time); 
      ED emot = new ED(); 
      emot.edetect("str"); 
      try { 
       Thread.sleep(1); 
      } catch { 

      } 
      println("Value: " + emot.getvalue); 
      i = emot.getvalue; 
       } 
+0

所以你想在最后回到我?你想在哪里使用该值? – stinepike

+4

使用Future和ExecutorService – MadProgrammer

+0

@SinePike是我想为另一个类使用'i'值,但多次运行线程 – VijayRagavan

回答

0

在多线程环境中,我们可以使用Executer服务从线程返回值。此功能可从JDK 5

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html

例子:

public class MyThread implements Callable{ 

    @Override 
    public String call(){ 
     Thread.sleep(2000); 
     return "Hello"; 
    } 

    public static void main(String args[]){ 
      ExecutorService executor = Executors.newFixedThreadPool(5); 
      Callable<String> callable = new MyThread(); 
      String value = executor.submit(callable); 
      System.out.println("The returned value is : "+value); 
      executor.shutdown(); 
    } 

} 

这是你可以从线程返回值的方式。

1

就我得到你的问题你有4个线程返回计算后的一些值。这里有几个想法:

  1. 如果你的线程返回一些结果使用Callable<V>其他Runnable
  2. 您可以使用ExecutorService提交您的任务(线程),并将获得Future<V>Future<?>,具体取决于它是否是CallableRunnable
  3. 如果您想接收所有线索的结果,您可以提交全部并获取期货,然后调用future.get哪些阻止,直到收到结果。如果你想从任何线程接收结果,那么在这种情况下,你也可以使用ExecutorCompletionService,它以接收的顺序维护一个结果队列。
0

您可以使该对象,emot,一个类变量。这样,当您在主线程中创建新对象时,可以通过getter方法访问该值。

public static void main(String[] args) { 
    //Your code 

    YourRunnableClass r = new YourRunnableClass(); 
    Thread yourThread = r; 
    yourThread.start(); 

    //other code 

    r.getValue() //The value you are trying to get 
} 

public class YourRunnableClass implements Runnable { 

    private ED emot; 

    public int getValue() { 
     return emot.getvalue(); 
    } 

    public void run() { 
     //Your Code 
    } 
} 
+0

Iam无法分配YourRunnableClass r = new YourRunnableClass(); Thread yourThread = r;类型不匹配不能从YourRunnableClass转换为线程 – VijayRagavan