Blog Detail

  • Home
  • Callable Vs Runnable

Callable Vs Runnable

In this blog I explain you difference between callable and runnable interface with sample code.

RunnableCallable
Has run() methodHas call() method
return type is voidreturn type is Future
can run using Thread classCan’t to run using Thread class
Can run using executor service. execute or submit method.
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(runnableObj);
service.submit(runnableObj);
Can run using executor service submit method only.
ExecutorService service = Executors.newSingleThreadExecutor();
service.submit(callableObj);

Sample Program

package com.samplecoder.threading;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RunnableVsCallable {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Runnable runnableObj = new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("Running runnable");
			}
		};
		
		Callable<String> callableObj = new Callable<String>() {

			@Override
			public String call() throws Exception {
				// TODO Auto-generated method stub
				System.out.println("Running callable");
				return null;
			}
		};
		
		ExecutorService service = Executors.newSingleThreadExecutor();
		service.execute(runnableObj);
		service.submit(runnableObj);
		service.submit(callableObj);
	}

}

Result

Running runnable
Running runnable
Running callable

Write a comment