Home / Java Programming / Threads :: Discussion

Discussion :: Threads

  1. class Test
    {

     public static void main(String [] args)
     {
         printAll(args);

     }
      public static void printAll(String[] lines)
      {
      for(int i = 0; i

      {
          System.out.println(lines[i]);
          Thread.currentThread().sleep(1000);
        }
      }
    }

    the static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?

     

     

  2. A.

    Each String in the array lines will output, with a 1-second pause.

    B.

    Each String in the array lines will output, with no pause in between because this method is not executed in a Thread.

    C.

    Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread.

    D.

    This code will not compile.

    View Answer

    Workspace

    Answer : Option D

    Explanation :

    D. The sleep() method must be enclosed in a try/catch block, or the method printAll() must declare it throws the InterruptedException.

    A is incorrect, but it would be correct if the InterruptedException was dealt with.

    B is incorrect, but it would still be incorrect if the InterruptedException was dealt with because all Java code, including the main() method, runs in threads.

    C is incorrect. The sleep() method is static, so even if it is called on an instance, it still always affects the currently executing thread.

     


Be The First To Comment