• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Threads

 
srilatha annepu
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Henry Wong
author
Marshal
Pie
Posts: 20886
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right right..

Since here two instances are different, so both can enter in the synchronized method at the same time.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic