How to create Multithreading program in java

class Multi extends Thread
{
    public void run()
    {
        System.out.println("thread is running...");
    }

    public static void main(String args[])
    {
        Multi t1 = new Multi();
        t1.start();
    }
}

This program illustrates an example of a multi-threaded program in Java by inheriting the Thread class and overrides the methods through run() called on the new thread with start().
Step-by-Step Breakdown:
1.  Class Declaration and Inheriting Thread: 
class Multi extends Thread {
The Multi class extends the Thread class, meaning that this class will inherit all the properties and methods of the Thread class. By extending Thread, we can define a custom behavior for the thread by overriding the run() method.
2. Overriding the run() Method:
public void run() {
       System.out.println("thread is running.");
 }
Overrides the run() method. This is the method that holds the code that will be executed when the thread is started.
For this example, when the thread is run, it will merely print the message "thread is running." to the console.
3. Main Method - Creating and Starting the Thread: 
public static void main(String args[]) {
       Multi t1 = new Multi();
       t1.start();
   }

Inside the main() method:

  • A new instance of the class Multi is declared: Multi t1 = new Multi();.

The above line declares a new instance of class Multi, t1 represents the thread.

  • The start() method is called on the object of type thread, t1: t1.start();. This starts a new thread of execution. It calls the run() method internally.

4. Execution Flow:

Important Notes:

  • Calling the start() method does not call the run() method directly. Rather, it gets the thread started and running and it is when the JVM schedules the thread to run that it calls the run() method.
  • If we do not override the run() method, then the Thread class’s run() method would be called (which does nothing), but here we override it with our own behavior, printing the message.

Output:

The output of this program will be:

thread is running.

Explanation of the Output:

  • The thread t1 starts and runs the run() method, printing “thread is running.”.
  • The actual order of execution is virtually unpredictable since it depends on how the operating system threads schedule. For example, since this main() method has only one print statement and no other important code, the output should be expected once the thread is executed below.

Conclusion:

It creates a new thread, starts it, and prints a message from the run() method, which is called by the thread. This is the simplest demonstration of threading in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *