Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Value from Multi Threading? [duplicate]

My problem is, i just want to return value from Multi threading out of 4 threads running concurrently in Multiple times. I need a return value for every times thread calls and run. Please justify me thank you, My code snippet looking like this, Thread1: i was calling java to native library function, function returns integer value.

 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;
                }
like image 922
VijayRagavan Avatar asked Oct 31 '25 12:10

VijayRagavan


2 Answers

As far as I got your problem you have 4 threads which return some value after computation. Here are few ideas:

  1. If your thread returns some result use Callable<V> else Runnable.
  2. You can use ExecutorService to submit your task (thread) and will get Future<V> or Future<?> depending on whether it is Callable or Runnable.
  3. If you want to receive result of all the threads you can submit all and get futures and then invoke future.get which blocks until result is received. If you want to receive result from any of the threads then in that case you can also use ExecutorCompletionService as well which maintains a queue of results in whatever order they are received.
like image 124
akhil_mittal Avatar answered Nov 03 '25 04:11

akhil_mittal


In multi threaded environment, we can return the values from thread by using Executer Service. This feature is available from JDK 5.

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

Example :

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

}

This is the way you can return the values from thread.

like image 28
Chandra Shekhar Goka Avatar answered Nov 03 '25 04:11

Chandra Shekhar Goka