
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Can we synchronize abstract methods in Java?
- Can we call run() method directly instead of start() in Java
- How can we run Matplotlib in Tkinter?
- Can we inherit a final method in Java?
- Can we override a start() method in Java?
- Can we override a protected method in Java?
- Can we overload Java main method?
- What will happen if we directly call the run() method in Java?
- How can we run a MySQL statement without termination semicolon?
- Can we execute a java program without a main method?
- Can we overload or override a static method in Java?
- Can we override a private or static method in Java
- Can we return this keyword from a method in java?
- Can we declare a main method as private in Java?
- Can we define an enum inside a method in Java?
Advertisements