Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Synchronized Thread doubt  RSS feed

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package may25th;

class Synchr extends Thread {
synchronized void method1() throws InterruptedException {
for (int i = 0; i < 5; i++) {
System.out.println("method1-------" + i+ " "+Thread.currentThread().getName());
Thread.sleep(1000);
}
}

synchronized void method2() throws InterruptedException {
for (int i = 0; i < 5; i++) {
System.out.println("method2-------" + i+" "+Thread.currentThread().getName());
Thread.sleep(1000);
}
}

public void run() {
try {
method1();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
try {
method2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public class ThreadSynch2 {
public static void main(String[] args) {
Synchr s = new Synchr();
s.setName("one");
s.start();
Synchr s1 = new Synchr();
s1.setName("two");
s1.start();

}

}

The ooutput of the above program is
method1-------0 one
method1-------0 two
method1-------1 one
method1-------1 two
method1-------2 one
method1-------2 two
method1-------3 one
method1-------3 two
method1-------4 one
method1-------4 two
method2-------0 one
method2-------0 two
method2-------1 one
method2-------1 two
method2-------2 one
method2-------2 two
method2-------3 one
method2-------3 two
method2-------4 one
method2-------4 two

I could not understand why thread 2 is called before one completes even though the method is synchronized.
Sorry if there was any mistake in this
Please clarify me
 
Greenhorn
Posts: 17
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In order to synchronize 2 threads, the synchronized object must be the same. In your code, each thread is synchronizing on its own Thread object, which is meaningless.
 
Anudeep Duvvuri
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya i got it after posting here thank you for your reply
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!