Interview question
What are the ways to create threads in Java? Explain Thread class vs Runnable. Java में threads बनाने के तरीके कौन से हैं? Thread class vs Runnable explain करें।
Answer
Threads can be created in two ways: extending Thread class or implementing Runnable interface. Runnable is preferred as Java doesn't support multiple inheritance. Both approaches have different advantages.
| Method | Syntax | Advantages | Disadvantages |
|---|---|---|---|
| Thread Class | class MyThread extends Thread | Direct access to Thread methods | Can't extend other class |
| Runnable Interface | class MyRun implements Runnable | Can extend another class | Need Thread wrapper |
// Method 1: Extending Thread class
public class MyThread extends Thread {
public void run() {
System.out.println('Thread is running');
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Don't call run() directly
}
}
// Method 2: Implementing Runnable (PREFERRED)
public class MyRunnable implements Runnable {
public void run() {
System.out.println('Runnable is running');
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
}
}
// Method 3: Lambda expression (Java 8+)
new Thread(() -> {
System.out.println('Lambda thread');
}).start();
// Method 4: Anonymous class
new Thread(new Runnable() {
public void run() {
System.out.println('Anonymous thread');
}
}).start();
// Important: Always call start(), never run()
// start() creates new thread and calls run()
// run() executes in same thread
t.start(); // Correct
t.run(); // Wrong - doesn't create new threadThreads बनाने के तरीके:
1. Thread class extend करना:
public class MyThread extends Thread {
public void run() { }
}
MyThread t = new MyThread();
t.start();
2. Runnable implement करना (BEST):
public class MyRun implements Runnable {
public void run() { }
}
Thread t = new Thread(new MyRun());
t.start();
3. Lambda (Java 8+):
new Thread(() -> {
// code
}).start();
Important: start() करो, run() नहीं!Was this answer clear?