Thread:
- Directly represents a thread.
- Encapsulates both the thread’s creation and execution.
- Less flexible due to the single inheritance constraint.
Creating a Thread by Extending the Thread Class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread(); // Creating an instance of MyThread
t1.start(); // Starting the thread
}
}
Runnable:
- Represents a task to be executed by a thread.
- More flexible, allowing the class to inherit from other classes.
- Encouraged for scenarios where you need to separate task definition from thread management.
Creating a Thread by Implementing the Runnable Interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is running.");
}
}
public class RunnableExample {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable(); // Creating an instance of MyRunnable
Thread t1 = new Thread(runnable); // Creating a Thread instance and passing the Runnable object
t1.start(); // Starting the thread
}
}

Hinterlasse einen Kommentar