Callable

public class CallableExample {

  public static void main(String[] args) throws Exception {

    String text = "Ala ma kota";
    ExecutorService es = newFixedThreadPool(3);
    int result = 0;
    for (String word : text.split(" ")) {
      Future<Integer> fut = es.submit(callable(word));
      result += fut.get();

    }
    es.shutdown();
    out.println("Number of non-space chars: " + result);
  }

  static Callable<Integer> callable(final String word) {
    return new Callable<Integer>() {

      @Override
      public Integer call() throws Exception {
        out.println(threadName() + word);
        return word.length();
      }
    };
  }

  static String threadName() {
    return Thread.currentThread().getName() + ",";
  }

Result:
pool-1-thread-1,Ala
pool-1-thread-2,ma
pool-1-thread-3,kota
Number of non-space characters: 9

Note: you execute Runnable and submit Callable on the ExecutorService. The get method on Future is bloking operation, waiting for the result.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s