In Java, there are two primary ways to create threads:
*1. Extending the Thread Class*
```
public class MyThread extends Thread {
@Override
public void run() {
// Thread code here
}
}
// Usage
MyThread thread = new MyThread();
thread.start();
```
*2. Implementing the Runnable Interface*
```
public class MyRunnable implements Runnable {
@Override
public void run() {
// Thread code here
}
}
// Usage
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
```
*Other Methods:*
*3. Using Anonymous Classes*
```
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// Thread code here
}
});
thread.start();
```
*4. Using Lambda Expressions (Java 8 and later)*
```
Thread thread = new Thread(() -> {
// Thread code here
});
thread.start();
```
*5. Using Executor Framework (Java 5 and later)*
```
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
@Override
public void run() {
// Thread code here
}
});
```
*6. Using Callable and Future (Java 5 and later)*
```
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = new Callable<String>() {
@Override
public String call() {
// Thread code here
return "Result";
}
};
Future<String> future = executor.submit(task);
```
*Comparison:*
| Method | Advantages | Disadvantages |
| --- | --- | --- |
| Extending Thread | Simple, easy to understand | Limited flexibility, can't extend other classes |
| Implementing Runnable | Flexible, can extend other classes | More verbose |
| Anonymous Classes | Convenient for small tasks | Limited readability |
| Lambda Expressions | Concise, easy to read | Limited to single-method interfaces |
| Executor Framework | Efficient, scalable | More complex setup |
| Callable and Future | Allows return values, exceptions | More complex setup |
Choose the method that best fits your use case, considering factors like readability, maintainability, and
performance.
Would you like more information on threading or concurrency in Java?