run()
logic.
Thread
class.
Runnable
interface.
Thread
class:Thread
and override run()
with the work to perform.
class MyThread extends Thread
{
@Override
public void run()
{
System.out.println("Thread task is executed...");
}
}
Thread
class:
MyThread t1 = new MyThread(3);
start()
(not run()
) to move to Runnable state and then Running state.
t1.start(); // schedules thread to run concurrently
class MyThread extends Thread
{
@Override
public void run()
{
System.out.println("Thread task is executed...");
}
}
public class MainApp
{
public static void main(String[] args)
{
MyThread t = new MyThread();
t.start();
}
}
Runnable
interface:Runnable
and override run()
with the work to perform.
class MyRunnable implements Runnable
{
@Override
public void run()
{
System.out.println("Thread task is executed...");
}
}
Runnable
and pass it to Thread
:
Runnable
class and pass it to a Thread
object.
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
start()
on the Thread
object to move it into the Runnable and then Running state.
t1.start(); // schedules thread to run concurrently
run()
on the Runnable
, it executes like a normal method inside the current thread.
class MyRunnable implements Runnable
{
@Override
public void run()
{
System.out.println("Thread task is executed...");
}
}
public class MainApp
{
public static void main(String[] args)
{
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
}
}
start()
and run()
methods:start()
method:
run()
method in a separate call stack.
run()
method:
Runnable
interface is generally preferred for real-world projects because:
Runnable
object can be used for multiple threads).
Thread
class is mostly used for quick examples or simple threads where inheritance is not an issue.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.