Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to notify() the main method in the given code snippet  RSS feed

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the given code snippet

code
-------------------------------------
public class WaitTest {
public static void main(String [] args) {
System.out.print("1 ") ;
synchronized(args) {
System.out.print("2 " ) ;
try {
args.wait();
}
catch(InterruptedException e){}

}
System.out.print("3 ");
}
}

---------------------------------------------
code

Here since there are no threads to notify the main()method the statement System.out.print("3 "); never gets executed.And i cannot use the non static notify() from a static context.In this case how will I notify the main() method.
 
Marshal
Posts: 58421
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code button rather than writing "code."

You would have to create another object and get that to notify. Which would have to be from a new thread.

I trust this is a party trick, and you aren't using such code in real life.
 
author
Marshal
Posts: 23439
138
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Here since there are no threads to notify the main()method the statement System.out.print("3 "); never gets executed.And i cannot use the non static notify() from a static context.In this case how will I notify the main() method.



No black magic here. It must be done from another thread. This thread needs access to the args array, which it will use to synchronize, and call notify().

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!