aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread with synchronized method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread with synchronized method" Watch "Thread with synchronized method" New topic

Thread with synchronized method

tural ferhadov

Joined: Oct 20, 2012
Posts: 7
When 2 threads is running how the result can be?

class ThreadTest implements Runnable{
synchronized void hit(long n){
for (int i=1;i<3;i++){System.out.print(n+" "+i)}

public void run(){

public static void main(String ... args){
new Thread(new ThreadTest()).start();
new Thread(new ThreadTest()).start();


As I understand how threads work, since hit is synchronized for loop in hit method must finish, before next thread calls this method..So result must be 4-1 4-2 5-1 5-2..
Is it possible to have result like 4-1 5-1 5-2 4-2.? If yes how?

Any help would be appriciated.

Thanks in advance
Konstantinos Alvertis

Joined: May 05, 2013
Posts: 11

Dear tural ferhadov

Yes it is possible to have the second result !

You have two threads with two different Runnable targets.

new Thread(Runnable_target1);
new Thread(Runnable_target2);

So each thread gets the lock of a different object.
The keyword synchronized in the method "hit"lets only the thread that has the lock of the particular object to execute the code(into the method).
Each object has one lock.

Konstantinos Alvertis

Joined: May 05, 2013
Posts: 11

Try this:

ThreadTest th = new ThreadTest();
new Thread(th).start();
new Thread(th).start();

wood burning stoves
subject: Thread with synchronized method
Similar Threads
from John Hunt mock-thread suspend and resume
Thread functioning help
Use 2 Threads
Question on thread
testing locks.