24
Feb

Ways to create Java threads baseds on Thread, Runnable, Callable

Java threads
=============

Ways to create Java threads baseds on Thread, Runnable, Callable 


1. Extend Thread
=================

package JavaConcurrency;

public class ExampleThread extends Thread {
	
	@Override
	public void run() {
		System.out.println("Via Thread ");
	}

}


client:		Thread t = new Thread(new ExampleThread());
		t.start();


2. Implement Runnable:
=======================
package JavaConcurrency;

public class ExampleRunnable implements Runnable {

	public void run() {
		System.out.println("Via Runnable ");
	}
}


Clinet:		Thread t = new Thread(new ExampleRunnable());
		t.start();



3. Implement Callable:
=======================

package JavaConcurrency;

import java.util.concurrent.Callable;

public class ExampleCallable implements Callable {

	public Object call() throws Exception {
		return "Via Callable ";
	}
}


Client:		FutureTask future = new FutureTask(new ExampleCallable());
		Thread t = new Thread(future);
		t.start();
		
		Object response = future.get();
		System.out.println(response);



Output:

Via Runnable 
Via Thread 
Via Callable