Explanation
This Java program demonstrates how to create and run multiple threads concurrently using two common approaches: extending the Thread class and implementing the Runnable interface.
-
Thread1Class: This class extends Java's built-inThreadclass. To make an object ofThread1executable as a separate thread, it overrides therun()method. Therun()method defines the task that this thread will perform. In this case,Thread1simply prints "Thread 1: " followed by numbers from 1 to 3. -
Thread2Class: This class implements theRunnableinterface. TheRunnableinterface also requires implementing arun()method, which defines the task for the thread. Similar toThread1,Thread2'srun()method prints "Thread 2: " followed by numbers from 1 to 3. The key difference here is thatThread2is not aThreaditself; it defines a task that aThreadobject can execute. -
MultipleThreadClass (Main Class):- The
mainmethod is the entry point of the program, which initially runs on the main thread. - Inside
main, an objectt1ofThread1is created. SinceThread1extendsThread,t1is already a thread object. - An object
t2_taskofThread2is created. Thist2_taskobject represents the task to be executed. - A new
Threadobjectt2is then created, passingt2_task(theRunnableinstance) to its constructor. This effectively "wraps" theRunnabletask within aThreadobject. - Finally,
t1.start()andt2.start()are called. Thestart()method is crucial: it initiates a new thread of execution fort1andt2respectively and then calls theirrun()methods. It does not directly callrun(). Ifrun()were called directly, the code would execute sequentially on the main thread, defeating the purpose of multithreading. - Because
t1andt2are now independent threads, theirrun()methods will execute concurrently. The Java Virtual Machine's (JVM) thread scheduler will determine when each thread gets CPU time, leading to an interleaved output of "Thread 1" and "Thread 2" messages.
- The