Exmaple of multithread (use Callable)


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //http://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6
  2. import java.util.*;
  3. import java.util.concurrent.*;
  4.  
  5. public class CallableExample {
  6.  
  7. public static class WordLengthCallable
  8. implements Callable {
  9. private String word;
  10. public WordLengthCallable(String word) {
  11. this.word = word;
  12. }
  13. public Integer call() {
  14. return Integer.valueOf(word.length());
  15. }
  16. }
  17.  
  18. public static void main(String args[]) throws Exception {
  19. ExecutorService pool = Executors.newFixedThreadPool(3);
  20. Set<Future<Integer>> set = new HashSet<Future<Integer>>();
  21. for (String word: args) {
  22. Callable<Integer> callable = new WordLengthCallable(word);
  23. Future<Integer> future = pool.submit(callable);
  24. set.add(future);
  25. }
  26. int sum = 0;
  27. for (Future<Integer> future : set) {
  28. sum += future.get();
  29. }
  30. System.out.printf("The sum of lengths is %s%n", sum);
  31. System.exit(sum);
  32. }
  33. }

URL: http://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.