java multi-threading callable demo

Multi threading is to spin up multiple threads to do stuff concurrently, each tread contains one running task. In java, the Runnable and Callable interfaces both can be used to do multi-threading. The differece is that The callable allow you to return the result when the task is done but the Runnable doesn’t return anything when done. The concept of callable is similar to the Promise in node.js such that the program started a task, then go on to do other stuffs, but it will get back to the task with the result when the task is completed.

Here is a basic usage of using the Callable interface and return the result of type String when the task is done. The call method can be rewritten to return other types of data according to your needs. The call method in the callable object is triggered by submitting it to the ExecutorService pool object. The submit method will return a Future object containing the result from the callable call method. The result from the Future object can then be retrieved by using the get() method of the Future object.

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:

Done counter0
Done counter1
Done counter2
Done counter3
Done counter4
Done counter5
Done counter6
Done counter7
Done counter8
Done counter9

Search within Codexpedia

Custom Search

Search the entire web

Custom Search