Programming |
@Override Public void run(){ //statements; }2. Pass the runnable into Thread class
Thread thread = new Thread(new Runnable());3. Start the thread by calling start() method on thread class object.
thread.start();Program
public class ThreadUsingRunnable implements Runnable { @Override public void run() { System.out.println("Inside the run() method."); } public static void main(String[] args) { ThreadUsingRunnable runnable = new ThreadUsingRunnable(); Thread thread = new Thread(runnable); thread.start(); } }Output
Inside the run() method.
@Override Public2. Convert the callable to runnable because thread class doesn’t has a constructor which takes callable as a parameter.call() throws Exception{ //statements; }
FutureTask3. Pass the converted runnable to Thread classfutureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);4. Start the thread by calling start() method on thread class object
thread.start();Program
public class ThreadUsingCallable implements CallableOutput{ @Override public String call() throws Exception { return "Inside the call() method."; } public static void main(String[] args) throws InterruptedException, ExecutionException { ThreadUsingCallable callable = new ThreadUsingCallable(); FutureTask futureTask = new FutureTask<>(callable); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); } }
Inside the call() method.
Runnable(I) | Callable(I) |
---|---|
Introduced in Java 1.0 |
Introduced in Java 1.5 |
run() method needs to be overridden. public abstract void run(); |
call() method needs to be overridden V call() throws Exception; |
Run() method cannot return any value back to the calling thread. |
Call() method can return any type of value back to the calling thread |
run() method cannot throw a check exception |
call() method can throw any checked exception |
Thread class constructor can take a runnable object as a parameter |
There is no constructor in thread class which takes a callable object, therefore callable must be converted to runnable type |