Sample multithreading program using Callable Interface

Step 1: Create “” and paste the below code,

package runnableandcallable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import runnableandcallable.CallingThread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainThread{
	private static ExecutorService service = Executors.newFixedThreadPool(10); 	//connection pool

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

		List<CallingThread> threads = new ArrayList<CallingThread>(); //ArrayList to store the threads with CallingThread Type
		CallingThread ct = null;

		for(int i=1;i<=5;i++){	// 5 threads are created
			ct = new CallingThread(i);	//calling CallingThread constructor of the CallingThread class.
			threads.add(ct);	// Storing the threads with theirs tasks.
		service.invokeAll((Collection<? extends Callable<CallingThread>>) threads);	//invoking all the threads using connection pool



Step 2: Create “” and paste the below code,

package runnableandcallable;

import java.util.concurrent.Callable;
import runnableandcallable.Businessprogram;

public class CallingThread implements Callable{
	int x;
	Businessprogram bp = new Businessprogram();
	public CallingThread(int x) {

	public Object call() throws Exception {
		//created thread calls the Add funcion of Businessprogram class. (5 times it called, because in the MainThread class we have created 5 threads
		System.out.println("Thread No "+x);	//
		return x;	//return statement is mandatory for the call method.



Step 3: Create the “” and paste the below code,

package runnableandcallable;

public class Businessprogram {
	public int Add(){
		int a=10;
		int b=20;
		System.out.println("Total =" +(a+b));
		return (a+b);


Step 4: Run the program.


Total =30 (you will get five times, since we have created 5 threads here).

Note: Program explanations are given as comments in the respective files.

Thanks for reading this post……..!!!

1,105 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.