Multithreading with Runnable Interface
Course: Object-Oriented Programming in JAVA Lab (BCA39109) | Semester: BCA 3rd Sem
This project demonstrates the creation and execution of multiple threads in Java using the Runnable interface. It effectively illustrates concurrent execution, thread suspension, and exception handling within a multithreaded environment.
- Runnable Interface: The class implements
java.lang.Runnable, which is the preferred approach for thread creation as it allows the class to extend another class if needed (unlike extending theThreadclass directly). - Thread Lifecycle (
startvsrun): The program explicitly usest1.start()to spawn a new call stack for concurrent execution, rather than just callingrun()which would execute synchronously. - Thread Suspension (
sleep): UtilizingThread.sleep(500)to pause the thread execution for exactly 500 milliseconds, demonstrating how the CPU switches context betweenThread-1andThread-2. - Exception Handling: Using a
try-catchblock to handleInterruptedException, which is required whenever a thread is forced to sleep or wait.
To run this program, ensure you have the Java Development Kit (JDK) installed on your machine.
- Open your terminal or command prompt.
- Navigate to the directory containing the file.
- Compile the Java code: