Win a copy of Hands On Software Engineering with Python this week in the Jython/Python 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
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

Lock Mechanism ?  RSS feed

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
}
System.out.println("Total is: " + b.total);
}
}
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this) {
for(int i=0;i<100;i++) {
total += i;
}
notify();
}
}
}



Can somebody please explain the lock mechanism in the above code ?

Regards
sid
 
Ranch Hand
Posts: 516
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

check the following code (your code) with comments.
Please read the comments in the numerated order (1-2-3-4-5-6-7)




In other words, the synchronize ensure that only a single thread can synchronize and execute inside the block.
The "wait" will make the thread wait until the other thread notify it, and also release the "lock" on the synchronized object.
You cannot "wait" or "notify" outside of a synchronized block.

Anyone else feel free to provide more or better details, it is not too easy to describe

Regards,
Alex
[ January 22, 2008: Message edited by: Alex Belisle Turcot ]
 
I'm still in control here. LOOK at this tiny ad!
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!