如何 return 从多线程中获取价值?

How to return Value from Multi Threading?

我的问题是,我只想 return 从 4 个线程中的多线程中 运行 并发地 运行 计算值。每次线程调用和 运行 都需要一个 return 值。请证明我的理由,谢谢,我的代码片段看起来像这样,Thread1:我正在调用 java 到本机库函数,函数 returns 整数值。

 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;
                }

就我遇到的问题而言,您有 4 个线程,return 计算后有一些值。这里有一些想法:

  1. 如果您的线程 return 有一些结果使用 Callable<V> 否则 Runnable
  2. 您可以使用ExecutorService提交您的任务(线程),将获得Future<V>Future<?>取决于它是Callable还是Runnable .
  3. 如果你想接收所有线程的结果,你可以提交所有线程并获取期货,然后调用 future.get,它会阻塞直到收到结果。如果你想从任何线程接收结果,那么在这种情况下你也可以使用 ExecutorCompletionService 以及它维护一个结果队列,无论它们被接收到的顺序如何。

你可以使那个对象,emot,成为一个 class 变量。这样,当您在主线程中创建新对象时,您可以通过 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
    }
}

在多线程环境下,我们可以return使用Executer Service从线程获取值。此功能从 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();
    }

}

这是您可以 return 来自线程的值的方法。