Creating Threads
Thread class and Runnable interface
Creating Threads
Threads can be created using Thread class or Runnable interface.
Code Examples
Extending Thread
java
1
2class MyThread extends Thread {
3 public void run() {
4 System.out.println("Thread running");
5 }
6}
7new MyThread().start();
8 Using Runnable (preferred)
java
1
2Runnable r = () -> System.out.println("Runnable thread");
3new Thread(r).start();
4 Use Cases
- Task execution
Common Mistakes to Avoid
- Calling run() instead of start()