- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements