The Java language Program supports multi threads. The synchronized is a keyword used in Java ensures that only one Java thread execute an object's synchronized method at a time. The concept lies on the thread, that allows the threads to wait for resources to become available and also notify the thread that makes resource available to notify other threads are on the queues for the resources.
Understand with Example
The Tutorial want to explain you a code that help you in understanding Java Method Synchronized. We have a class Synchronized Method. In order to make a method Synchronized, we add synchronized keyword to the method. The synchronized int get Count ( ) method return you the count of thread executed in a code.
The static void print(String ms) includes a Thread.currentThread ( ).get Name( ) return you the name of the current thread. The print ln print the thread Name.
Inside the main method, The run ( ) method used to create a thread, that causes the thread to be started and each thread executed separately in the application. The print ln method print the count of thread by calling from get Count ( ).
Thread threadA =new Thread(Runnable,"Thread A"): The new is used to describe that thread is created but not yet started.
Thread.start ( ): This causes the thread to start and ready for execution.
Thread.sleep ( ):This causes the currently executing thread to sleep (cease execution) as per specified number of millisecond.
On execution the code show you the count of thread and execute each thread after 500 millisecond. In case the exception exists in try block,the catch block caught and handle the exception
Here is the code:
Output will be displayed as:
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial