Sample multithreading program using Callable Interface

Step 1: Create “MainThread.java” 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

	@SuppressWarnings("unchecked")
	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 “CallingThread.java” and paste the below code,

package runnableandcallable;

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

@SuppressWarnings("rawtypes")
public class CallingThread implements Callable{
	int x;
	Businessprogram bp = new Businessprogram();
	public CallingThread(int x) {
		this.x=x;
	}

	@Override
	public Object call() throws Exception {
		bp.Add();
		//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 “Businessprogram.java” 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 MainThread.java program.

Ouput:

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……..!!!

215 total views, 1 views today

Leave a Reply

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