You are here:   HomeJava ProgrammingMultithreadingExplain Thread Priorities in Multithreading
by Dinesh Thakur Category: Multithreading

This single sequence of executable statements within a program is known as a thread. In other words, a thread is s flow of execution of a task in a program so it known as a thread of execution or a thread of control.

You can make your class to behave as a thread by defining your class as a subclass of java .lang. Thread class and overriding its run () method which is the entry point for the new thread. This method contains the code that will be executed when the thread is started. We override this method because the run () method inherited from Thread class is empty so we redefine the method in the subclass in order to make the thread do something useful.

Once the subclass is defined, you just need to create an object of this class and invoke its start () method in the client program (i.e. in main () method) to start the thread. The start () method registers the thread with the thread scheduler. The scheduler might be part of the JVM or the host OS. The scheduler determines which thread is running on the CPU at any given time. Note that when you call the start () method for a Thread object it does not mean that it will execute immediately rather the scheduler places the thread in the queue for execution where it competes for CPU time with all other threads. Eventually the thread will execute when the other running thread release the CPU and at that time its run () method will be called. The new thread continues to run until the run () method exits, at which point it ceases to exist. Do not call the run () method directly. If you do so, it does not create a new thread, instead the run () method is simply executed in the caller's thread, just like any other method call.

Now let us consider a program that creates and executes a thread

class MyThread extends Thread

{
     private int threadNum;
     MyThread(int n)
     {
       threadNum = n;
     }
     public void run()
     {
       System.out.println("Thread Number " + threadNum + " is Running");
     }
}
      public class CreatingThread
   {
           public static void main(String[] args)
        {
              System.out.println("Main thread Start");
              MyThread t1 = new MyThread(1);
              MyThread t2 = new MyThread(2);
              MyThread t3 = new MyThread(3);
              t1.start(); // starts thread t1
              t2.start(); // starts thread t2
              t3.start(); // starts thread t3
              System.out.println ("Main thread Finished");
        }
  }

Creating Thread Using Thread Class in Java Example



What's New and Popular