aspose file tools*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Interaction" Watch "Thread Interaction" New topic
Author

Thread Interaction

k duffy
Greenhorn

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?

Regards

kd



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

}

}


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;
}
notify();
}
}

}
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!


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
k duffy
Greenhorn

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

Please kd
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread Interaction