• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread with synchronized method

 
tural ferhadov
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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(){
hit(Thread.currentThread.getId());
}

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
Greenhorn
Posts: 11
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 11
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:

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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic