Can we synchronize a run() method in Java?


Yes, we can synchronize a run() method in Java, but it is not required because this method has been executed by a single thread only. Hence synchronization is not needed for the run() method. It is good practice to synchronize a non-static method of other class because it is invoked by multiple threads at the same time.

Example

public class SynchronizeRunMethodTest implements Runnable {
   public synchronized void run() {
      System.out.println(Thread.currentThread().getName() + " is starting");
      for(int i=0; i < 5; i++) {
         try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() + " is running");
         } catch(InterruptedException ie) {
            ie.printStackTrace();
         }
      }
      System.out.println(Thread.currentThread().getName() + " is finished");
   }
   public static void main(String[] args) {
      SynchronizeRunMethodTest test = new SynchronizeRunMethodTest();
      Thread t1 = new Thread(test);
      Thread t2 = new Thread(test);
      t1.start();
      t2.start();
   }
}

Output

Thread-0 is starting
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is running
Thread-0 is finished
Thread-1 is starting
Thread-1 is running
Thread-1 is running
Thread-1 is running
Thread-1 is running
Thread-1 is running
Thread-1 is finished

Updated on: 28-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements