Explanation
This Java code demonstrates a fundamental way to achieve multithreading in Java by extending the Thread class. Multithreading allows a program to execute multiple parts of its code concurrently, meaning they appear to run at the same time, improving responsiveness and efficiency for certain tasks.
Here's a step-by-step breakdown:
-
Defining a Custom Thread (
MyThreadclass):- The
MyThreadclass is created byextendingthe built-injava.lang.Threadclass. This is the first way to create a thread in Java. - Inside
MyThread, there's a method calledrun(). This method is crucial because it defines the task that the new thread will execute. When a thread starts, it looks for and executes the code inside itsrun()method. - The
run()method contains aforloop that iterates from 1 to 5. In each iteration:- It prints a message to the console indicating the current thread and the iteration number (e.g., "Thread using Thread class: 1").
Thread.sleep(500)is called. This line tells the currently executing thread (in this case, ourMyThreadinstance) to pause its execution for 500 milliseconds (half a second). This pause allows us to visibly see the separate, concurrent execution if we had multiple threads.- The
Thread.sleep()method can throw anInterruptedException, which is a checked exception. Therefore, it must be enclosed in atry-catchblock. If another thread interrupts our sleeping thread, this exception would be caught, and its details would be printed.
- The
-
Starting the Thread (
ThreadClassandmainmethod):- The
ThreadClasscontains themainmethod, which is the entry point for any Java application. - Inside
main, an object of our customMyThreadclass is created:MyThread t1 = new MyThread();. At this point,t1is just a regular Java object, not yet an active thread. - The line
t1.start();is the key. Whenstart()is called, the Java Virtual Machine (JVM) performs two critical actions:- It allocates a new call stack for this new thread (
t1). - It then calls the
run()method oft1on this newly created call stack. This is what actually begins the concurrent execution of the code defined inMyThread'srun()method.
- It allocates a new call stack for this new thread (
- It's important to note that directly calling
t1.run()would simply execute therun()method as a regular method call within the main thread, without creating a new thread of execution.start()is essential for true multithreading.
- The
In essence, this code defines a simple task (printing numbers with a delay), wraps it in a custom Thread class, and then initiates that task on its own separate thread of execution, independent of the main thread.