• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized keyword use

 
samdeep aarzoo
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can we use synchronized keyword in method and block in threads question
and why synchronized keyword is used in stringbuffer methods
please help
 
Shaila Vijaya Raja
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider your class name as Test.

you have created a object as

Test te1 = new Test();
Test te2 = new Test();

Thread t1 = new Thread(te1);
Thread t2 = new Thread(te1);
Thread t3 = new Thread(te2)

now t1 and t2 are two thread class reference having the same object te1.

but t3 is the thread having a different object.

Keep in mind that each and every object has a lock on its own.

And you are having three seperate methods method1()method2() and method3() in your class and method1() and method2() are marked as synchronized.

Now consider your t1 is accessing the method1()( now the object te1 lock is owned by the thread t1 because method1() is synchronized).

now no other threads (example t2) having the same object te1 cannot access any other synchronized method in the class Test. but can access nonsynchronized method.

But the thread having the different object( example: t3) can acess a synchronized or non synchronized method.

If your synchronized method is marked as static then the whole class is said to be locked. In such a case, even no other thread having a different object(example t3) can access the synchronized method. But all the nonsynchronized method shall be accessed by any other threads.

With Regards
Shaila Vijaya Raja
 
samdeep aarzoo
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks shailavijayaraja ramasamy
thank u very much for this nice explanation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic