ProAnswers.org

Thread Synchronization in java?

When multiple threads wants to access the object at the same time avoiding multiple threads to access the same and giving access to one of the thread is called as thread synchronization. Thread synchronization can be done into two ways.

1.     Synchronized Block



2.     synchronized  Method



1.[b]Synchronized Block[/b]: Synchronizing a group of statements or part of a code is called as Synchronized Block.



[b]Syntax[/b]: Synchronized(object){



                     Statements;    }



2.[b]Synchronized Method[/b]: when we want to Synchronized all the statements in a method we go for synchronized method.



[b]Syntax[/b]: Synchronized returnType methodName(){



                        Statements;



                                    }



[b]Note[/b]: In the previous program multiple threads acting on the same object leading to data in consistency, to avoid the data inconsistency problem. We have to synchronize the threads acting on the same object.



[b]Ex[/b]: public Synchronized void run(){



            Same code previous programs;



                        }



When multiple threads are acting on synchronized objects then there is chance of other problems like ‘Deadlock’ occurring in the application.