Page 1 of 1

About Question enthuware.ocpjp.v7.2.1407 :

Posted: Thu May 08, 2014 4:48 pm
by ewebxml
For the following code the word "done" is never printed.

Code: Select all

public class MySecureClass
{
   public synchronized void doALotOfStuff()
   {
      try
      {
         LINE1: Thread.sleep(10000);
      }catch(Exception e){ }
   }
   public synchronized void doSmallStuff()
   {
      System.out.println("done");
   }
   public static void main(String args[]){
	   MySecureClass mySC = new MySecureClass();
	   mySC.doALotOfStuff();
   }
}
/* */
Is there something wrong with the way that I am calling the method
doALotOfStuff();?
-----
I selected option c)
done will never be printed

because for the code above "done" is never printed.



Please confirm.

Re: About Question enthuware.ocpjp.v7.2.1407 :

Posted: Thu May 08, 2014 10:49 pm
by admin
The question says, "Assume that there are two threads. Thread one is executing the doALotOfStuff() method and has just called LINE 1 and is sleeping. Now, Thread two decides to call doSmallStuff() method on the same object."

Your code does not do what the question asks. Your main method should be something like this:

Code: Select all

  public static void main(String args[]){
      final MySecureClass mySC = new MySecureClass();
      Thread t1 = new Thread(){
        public void run(){
          mySC.doALotOfStuff();
        }
      };
      t1.start(); 
      Thread t2 = new Thread(){
        public void run(){
          mySC.doSmallStuff();
        }
      };
      t2.start();
   }

HTH,
Paul.

Re: About Question enthuware.ocpjp.v7.2.1407 :

Posted: Fri Feb 06, 2015 2:43 pm
by ewebxml
I understand that this question specifically states that there are 2 threads.
Q: Can you confirm that the same output will be generated with 1 thread (as in main below),
although this is what is not stated(or required) by the question?

Code: Select all

public class MySecureClass {
  public synchronized void doALotOfStuff() {
    System.out.println("Witin doALotOfStuff()");
      try {
        LINE1: Thread.sleep(10000);
      } catch (Exception e) {}
  }
  public synchronized void doSmallStuff() {		
    System.out.println("done");
  }
  /* main method with 1 thread*/
  public static void main(String args[]) {
    Thread t1 = new Thread(new Runnable() {
      public void run() {
        MySecureClass m1 = new MySecureClass();
        m1.doALotOfStuff();
        m1.doSmallStuff();
      }
    });
    t1.start();
  }
}
/* 
Program Output 
Witin doALotOfStuff()
done		// Note: This line is printed 10 seconds later
*/

Re: About Question enthuware.ocpjp.v7.2.1407 :

Posted: Fri Feb 06, 2015 9:11 pm
by admin
Yes, the output will be the same.