Return a value from a thread. : Collections Threads « Threads « Java






Return a value from a thread.

   

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
  public static void main(String args[]) throws Exception{
    ExecutorService es = Executors.newFixedThreadPool(3);
    Future<Double> f = es.submit(new Avg());
    Future<Integer> f2 = es.submit(new Factorial());

    System.out.println(f.get());
    System.out.println(f2.get());
    es.shutdown();
  }
}

class Avg implements Callable<Double> {
  Avg() {
  }

  public Double call() {
    return 0.0;
  }
}
class Factorial implements Callable<Integer> {
  Factorial() {
  }

  public Integer call() {
    return 1;
  }
}

   
    
    
  








Related examples in the same category

1.Java 1.5 (5.0) new features: PriorityQueueJava 1.5 (5.0) new features: PriorityQueue
2.Safe list copySafe list copy
3.Safe vector copySafe vector copy
4.Safe collection operationSafe collection operation
5.Java 1.5 (5.0) new feature: collection and thread
6.Java Thread Performance: Collection Test
7.Java Thread Performance: AtomicTest
8.Rhyming WordsRhyming Words
9.Communicate between threads using a Queue
10.Using a Thread-Local Variable
11.A work queue is used to coordinate work between a producer and a set of worker threads.
12.A multithreaded queue used for implementing producer-consumer style threading patternsA multithreaded queue used for implementing producer-consumer style threading patterns
13.Customized java.util.ArrayList: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
14.Customized java.util.HashMap: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
15.Customized java.util.TreeMap: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
16.Current set