Creating Threads in Java with Thread Class, Runnable Interface, and Lambda

🚀 Backend Systems | Post - 3 | How to create Threads in JAVA In the last posts, we understood Multithreading, and the difference between Concurrency and Parallelism , now lets learns how do we actually create threads in Java. 1. Extending the Thread Class You can create a thread by having a subclass which extends the Thread class and overriding the run() method. class MyThread extends Thread { @Override public void run() { System.out.println("Hello World"); } } MyThread t1 = new MyThread(); t1.start(); 2. Implementing Runnable Interface (this is usually recommended) This is the most commonly used approach in real-world systems having a class implements the runnable interface and overriding the run method. what is Runnable interface ? It is functional interface which has only one abstract function run. class MyRunnable implements Runnable { @Override public void run() { System.out.println("Hello World"); } } Thread t1 = new Thread(new MyRunnable()); t1.start(); 💡 Why is this better? --> as in java multilevel inheritance isn't possible with classes but possible with interface , since runnable is a interface because of that it allows for multilevel inheritance , this approach is usually better in backend systems. 3. Using Lambda (Modern Java🔥) In modern java we use lambda as a shortcut way to implement a functional interface , since Runnable is also a functional interface , we use this way when this line of code will only be used only by this thread. Thread t1 = new Thread(() -> { System.out.println("Hello World"); }); t1.start(); ⚠️ Common Mistake (VERY IMPORTANT) Most beginners think this will create a thread: Calling run() directly -->This will NOT create a new thread --> It just runs like a normal function call. --> the correct way is to always use start() to create a new thread. 🚀 Key Takeaways --> Runnable is better than Thread for better design. --> Lambda is a clean way to implement Runnable. --> start() creates a thread, run() does not. #Multithreading #Java #OperatingSystem #BackenedSystems

To view or add a comment, sign in

Explore content categories