Runnable Interface

Runnable Interface The Runnable interface in Java is another way to create and execute threads. It is preferred over extending the Thread class, especially when a class needs to extend another class as Java does not support multiple inheritance. Declaring a Thread with Runnable To use Runnable, implement the interface and pass the object to a Thread. class MyRunnable implements Runnable { public void run() { System.out.println("Runnable thread running..."); } } public class Main { public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread t = new Thread(myRunnable); t.start(); } } Advantages of Using Runnable Decouples task from thread mechanics. Allows class to extend another class. More flexible in multithreaded applications. Anonymous Runnable Example public class Main { public static void main(String[] args) { Thread t = new Thread(new Runnable() { public void run() { System.out.println("Anonymous Runnable running..."); } }); t.start(); } } Functional Interface & Lambda Expression (Java 8+) public class Main { public static void main(String[] args) { Runnable r = () -> System.out.println("Lambda Runnable running..."); Thread t = new Thread(r); t.start(); } } 🔗 Related Notes Thread Class Concurrent Programming Exception Handlers

May 8, 2025 · 1 min · Rohan

Concurrent Programming

Concurrent Programming Concurrent Programming in Java allows multiple threads to run simultaneously, making programs more efficient and responsive, especially for tasks that are independent or I/O-bound. Why Concurrency? Efficient CPU utilization Better performance in multi-core systems Responsiveness in interactive applications Threads in Java Java supports multithreading through the Thread class and Runnable interface. A thread represents a single sequence of execution within a program. Creating Threads 1. By Extending Thread Class class MyThread extends Thread { public void run() { System.out.println("Thread running..."); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // Starts a new thread } } 2. By Implementing Runnable Interface class MyRunnable implements Runnable { public void run() { System.out.println("Runnable thread running..."); } } public class Main { public static void main(String[] args) { Thread t = new Thread(new MyRunnable()); t.start(); } } Thread Lifecycle New Runnable Running Blocked/Waiting Terminated Synchronization Used to control thread access to shared resources to prevent data inconsistency. ...

May 8, 2025 · 1 min · Rohan