Which method must be implemented by all threads in Java?



While creating a thread class we must override the run() method of the Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method.

Example

class ThreadDemo extends Thread {
   private String threadName;

   ThreadDemo( String name) {
      threadName = name;
      System.out.println("Creating " +        threadName );
   }

   public void run() {
      System.out.println("Running " +          threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
           
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Thread " +      threadName + " interrupted.");
      }
      System.out.println("Thread " +     threadName + " exiting.");
   }
}

public class TestThread {
   public static void main(String args[]) {
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   }
}

Output

Creating Thread-1
Creating Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Monica Mona
Monica Mona

Student of life, and a lifelong learner


Advertisements