This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Interaction 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 Interaction" Watch "Thread Interaction" New topic

Thread Interaction

k duffy

Joined: Aug 29, 2004
Posts: 11
I accept the assertion that when it comes to threads very little is guaranteed.

But I believe that an assumption is being made in the following code.
From Sierra amd Bates pg 529.

This code assumes that ThreadA will get a lock on Thread "b" before "b" can start its loop. Is this a safe way of doing things? Yes I know it is only an example in a book.

Because if the loop in "b" got started before ThreadA got the lock then the following would happen:
ThreadA would be blocked at synchronized(b)
the wait in ThreadA would never receive the notify

Am I getting this right?



public class ThreadA {
public static void main(String [] args ){
ThreadB b = new ThreadB();
synchronized(b) {
System.out.println("ThreadA has the lock");
try {
System.out.println("Waiting for b to complete...");
catch (InterruptedException iEx) {}
System.out.println("Total is: " + );



class ThreadB extends Thread {
int total;

public void run() {
synchronized(this) {
System.out.println("ThreadB has the lock");
for(int i = 0; i<100; i++) {
total += i;

Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
I think the point of the book is that you shouldn't make those types of assumptions at all!

k duffy

Joined: Aug 29, 2004
Posts: 11
Could you suggest how to improve the code?

Please kd
I agree. Here's the link:
subject: Thread Interaction
Similar Threads
another thread question
Lock Mechanism ?
thread doubt
wait/notify confusion
Confused about Thread synchronization