Creating Thread using Runnable:
- It is an interface.
- It contains only one specification called run() method.
- We need to override run method to place thread logic.
- The class which is implementing Runnable interface is called Runnable object but not Thread.
interface Runnable
{
void run();
}
- Thread class is providing constructor to construct the thread from Runnable object.
- We cannot start Runnable object directly.
class Custom implements Runnable
{
public void run()
{
System.out.println("Thread logic...");
}
}
class CreateThread
{
public static void main(String[] args)
{
Custom obj = new Custom();
obj.start(); -> Error :
}
}
- We should create Thread by passing Runnable object as an input to Thread constructor.
- By invoking start() method, we can execute thread logic.
/*
class Thread
{
Thread(Runnable obj)
{
Construct thread from Runnable object
}
}
*/
class Custom implements Runnable
{
public void run()
{
System.out.println("Thread logic...");
}
}
class CreateThread
{
public static void main(String[] args)
{
Custom obj = new Custom();
Thread t = new Thread(obj);
t.start();
}
}