aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Threads" Watch "Threads" New topic
Author

Threads

srilatha annepu
Greenhorn

Joined: Jun 29, 2006
Posts: 28
can any one explain me below code how it is processed.

class Worker extends java.lang.Thread {
public void run() {
test();
}
synchronized void test() {
try {
System.out.println("X");
wait();
} catch (Exception e) {}
}
public static void main( String[] args ) {
new Worker().start();
new Worker().start();
}
}
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
One of your thread (could be first or second) enters in synchronized method and prints X and then comes in waiting state. Then second thread acquires the lock and enters in same synchronized method and prints X and it also comes in waiting state.

your program then will wait forever. You have to manually close program by Ctrl-C


Naseem


Asking Smart Questions FAQ - How To Put Your Code In Code Tags
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18712
    
  40

One of your thread (could be first or second) enters in synchronized method and prints X and then comes in waiting state. Then second thread ...


Since the two threads are synchronizing on different objects, they can actually context-switch at any time, or even run in parallel in a multiprocessor machine.

BTW, is this related to a SCJP question? Because we have another forum just for general thread questions.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
Right right..

Since here two instances are different, so both can enter in the synchronized method at the same time.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Threads