Thursday 19 January 2012

java.lang.Thread Objective Questions

1)
class Main implements Runnable {
    public void run() {
        System.out.println("thread");
    }

    public static void main(String args[]) {
        Main m = new Main();
        m.start();
    }
}
// What is the result of attempting to compile and run the program?

  1. Prints thread
  2. Prints Nothing
  3. Compile-time error
  4. Run-time error
Answer:Compile-time error.

start() method is declared with in java.lang.Thread class.So here to start the thread use following
Thread t=new Thread(m);
m.start();
It will start a new thread and prints the message 'thread'.


2)
class Main extends Thread{
   
    public void run(String s){
        System.out.println("thread");
    }
    public static void main(String args[]){
        Main m=new Main();
                m.start();
        }
}

What is the result of attempting to compile and run the program?
  1. Prints thread
  2. Prints Nothing
  3. Compile-time error
  4. Run-time error

Answer:Prints Nothing

The thread of execution -the new call stack-always begins by invoking the method run().But here overloaded
version of run() is used.Hence nothing will be printed.

3)
class Main extends Thread{
   
    public void run(){
        System.out.println("thread");
    }
    public static void main(String args[]){
        Main m=new Main();
        m.run();
        }
}
What is the result of attempting to compile and run the program?
  1. Prints 'thread',execution happen in a new thread.
  2. Prints 'thread',execution won't happen in a new thread.
  3. Prints Nothing
  4. Compile-time error
Answer :Prints 'thread',execution won't happen in a new thread.

if you call the run() method directly yourself, execution won't happen in a new thread of execution with a separate call stack. It will just happen in the same call stack as the code that you made the call from, just like any other normal method call.To start a new thread use m.start(),it will implicitly call run() method.

4)
class Main extends Thread{
   
    public void run(){
        System.out.println("thread");
    }
    public static void main(String args[]){
        Main m=new Main();
        m.start();
    }
}

What is the result of attempting to compile and run the program?
  1. Prints thread
  2. Prints Nothing
  3. Compile-time error
  4. Run-time error
Answer:Prints thread

The above code will start a new thread and prints the message 'thread'.Threads can be created in two different ways,either extends the java.lang.Thread class or implements the java.lang.Runnable interface.

5)

class Main implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String args[]) {
        Main m = new Main();
        Thread t = new Thread(m);
        t.setName("mythread");
        t.start();
    }
}
// What is the result of attempting to compile and run the program?
  1. Prints mythread
  2. Prints Nothing
  3. Compile-time error
  4. Run-time error
Answer :Prints mythread

Thread.currentThread(),which returns a reference to the currently executing thread.The getName(),setName(string) are used to get and set the name of a thread.

6)

class Main extends Thread {
    public void run() {
        System.out.print(" mythread ");
    }
    public static void main(String args[]) throws InterruptedException {
        Main m = new Main();
        m.start();
        m.join();
        System.out.println(" end ");
    }
}
// What is the result of attempting to compile and run the program?
  1. Prints mythread end
  2. Prints end mythread
  3. Compile-time error
  4. Run-time error
Answer:Prints mythread end

join() function to start a thread but tell it not to run until some other thread has finished.Here m.join() is used to wait the main thread until thread m is finished.Hence the result 'mythread end'.

7)

class Main extends Thread {
    public void run() {
        System.out.println("mythread");
    }
    public static void main(String args[]) throws InterruptedException {
        Main m = new Main();
        m.start();//Line 1
        m.join(); //Line 2
        m.start();//Line 3
    }
}
// What is the result of attempting to compile and run the program?
  1. Prints mythread
  2. Prints mythread and then run-time exception
  3. Prints Nothing
  4. Compile-time error
Answer:Prints mythread and then run-time exception

If you have a reference to a Thread, and you call start(), it's started. If you call start() a second time, it will cause an exception (an IllegalThreadStateException).

8)
class Main extends Thread{
   
    public void run(){
        System.out.println("thread");
    }
    public static void main(String args[]){
        Main m=new Main();//Line 1
        }
}
What is the result of attempting to compile and run the program?
  1. Prints thread
  2. Prints Nothing
  3. Compile-time error
  4. Run-time error
Answer :Prints Nothing

In order to start a thread we have to use the method 'start()' declared in java.lang.Thread class.So here if you use m.start() after line 1 ,a new thread will create and print the message 'thread'.

9)
class Main extends Thread {
    public void run() {
        System.out.println("mythread");
    }
    public static void main(String args[]) {
        Main m = new Main();
        m.start();
        m.join();
        System.out.println("end");
    }
}
// What is the result of attempting to compile and run the program?

  1. Prints mythread end
  2. Prints end mythread
  3. Compile-time error
  4. Run-time error
Answer:Compile-time error

For the method join() unhandled exception type InterruptedException.Either put join() inside try-catch blockor add throws clause to main method.

10)
class Main extends Thread {
    public void run() {
        System.out.println("mythread");
    }
    public static void main(String args[]) {
        Main m = new Main();
        m.start();
        Thread.sleep(1000);
        System.out.println("end");
    }
}
// What is the result of attempting to compile and run the program?
  1. Prints mythread end
  2. Prints end mythread
  3. Compile-time error
  4. Run-time error
Answer:Compile-time error

For the method sleep(() ,Unhandled exception type InterruptedException.Either put sleep() inside try-catch block or add throws clause to main method.

11)
Which of the following methods is not a member of the Object class?
  1. wait()
  2. notify()
  3. notifyAll()
  4. join()
Answer:join()

join() is a non-static method defined within the class java.lang.Thread.

12)
class A extends Thread {
  public void run() {
    try {sleep(10000);} catch (InterruptedException ie){}}
  public static void main(String[] args) {
    A a1 = new A();
    long startTime = System.currentTimeMillis();
    a1.start();
    System.out.print(System.currentTimeMillis() - startTime);
}}

What are the possible results of attempting to compile and run the program?
  1. Prints a number greater than or equal to 0
  2. The number printed must always be greater than 10000
  3. Compile-time error
  4. Run-time error
Answer:Prints a number greater than or equal to 0

Thread a1 will run for at least ten seconds, but the main method is likely to run to completion very quickly. The start method will return without waiting for thread a1 to complete. Since thread a1 immediately goes to sleep the thread that is processing the main method has an opportunity to complete the main method quickly. The number printed in the main method can be as small as zero.  

13)
class A extends Thread {String[] sa; public A(String[] sa) {this.sa = sa;}
  public void run() {synchronized (sa) {
  while (!sa[0].equals("Done")) {try {sa.wait();} catch (InterruptedException ie) {}
  }}System.out.print(sa[1] + sa[2] + sa[3]);}}
class B {  private static String[] sa = new String[]{"Not Done","X","Y","Z"};
public static void main (String[] args) {Thread t1 = new A(sa);
t1.start();synchronized(sa){sa[0] = "Done";sa[1]= "A";sa[2]="B";sa[3]="C";sa.notify();}}}
  1. Prints ABC
  2. Prints XYZ
  3. Compile-time error
  4. Run-time error
Answer:Prints ABC

Inside the main method, thread t1 is started and will move into the Running state at the discretion of the thread scheduler. The A.run method invokes the wait method on the String array object sa causing the thread to block until another thread invokes the sa.notify method. Before the B.main method invokes sa.notify, all of the elements of the String array object sa have already been updated.

14)
Which of the following methods are static members of the Thread class?

1. wait()
2. join()
3. run()
4. sleep()
5. yield()

Answer:sleep() and yield() are static methods declared within the class java.lang.Thread.

15)
Which of the following methods are deprecated members of the Thread class?

1. sleep()
2. stop()
3. suspend()
4. resume()
5. yield()
6. join()

Answer: stop(),suspend() and resume() .Every Java programmer should know that the deprecated methods should not be used in new programs.

16)
Which of the following thread state transitions model the lifecycle of a thread?

1. The Dead state to the Ready state
2. The Ready state to the Not-Runnable state
3. The Ready state to the Running state
4. The Running state to the Not-Runnable state
5. The Running state to the Ready state
6. The Not-Runnable state to the Ready state
7. The Not-Runnable state to the Running state

Answer:3,4,5&6

A dead thread can not be restarted.

17)
Which of the following methods name the InterruptedException in its throws clause?

1. run()
2. wait()
3. sleep()
4. join()
5. yield()
6. notify()

Answer:wait(),sleep(),join() declared within the class java.lang.Thread throws java.lang.InterruptedException.So always keep these functions within try-catch block else compile-time error will generate.

18)
class A implements Runnable {
  public void run() {System.out.print(Thread.currentThread().getName());}}
class B implements Runnable {
  public void run() {new A().run();
    new Thread(new A(),"T2").run();
    new Thread(new A(),"T3").start();}}
class C { public static void main (String[] args) {
    new Thread(new B(),"T1").start();}}

What is the result of attempting to compile and run the program?
  1. Prints: T1T1T1
  2. Prints: T1T2T3
  3. Prints: T1T1T3
  4. Prints: T1T3T3
Answer:Prints: T1T1T3

The Thread.currentThread method returns a reference to the currently executing thread. When the run method is invoked directly it does not start a new thread; so T1 is printed twice.

19)
class A extends Thread {
  private int i;
  public void run() {i = 1;}
  public static void main(String[] args) {
    A a = new A(); a.start(); System.out.print(a.i);
}}

What are the possible results of attempting to compile and run the program?
  1. Prints Nothing
  2. Prints 0
  3. Prints 1
  4. Prints 0 or 1
Answer:Prints 0 or 1

The new thread is started before the print statement, but there is no guarantee that the new thread will run before the print statement is processed. The guarantee could be provided by placing the method invocation expression a.join() before the print statement, but the invocation of the join method does not appear in the program. If the new thread runs before the print statement is processed, then 1 is printed. Otherwise, 0 is printed.

20)
class A extends Thread {
  public void run() {
    synchronized (this) {
      try {wait(5000);} catch (InterruptedException ie){}
  }}
  public static void main(String[] args) {
    A a1 = new A();
    long startTime = System.currentTimeMillis();
    a1.start();
    try {a1.join(6000);} catch (InterruptedException ie) {}
    System.out.print(System.currentTimeMillis() - startTime);
}}
What are the possible results of attempting to compile and run the program?
  1. The number printed is greater than or equal to 0
  2. The number printed is greater than 5000
  3. The number printed is greater than 6000
  4. Compile-time error
Answer:The number printed is greater than 5000

The notify method is never invoked on thread a1; so it will sleep for at least five seconds. The invocation of the join method forces the main thread to wait for the completion of thread a1. The argument of 6000 will allow the main thread to wait for six seconds if necessary, but we know that thread a1 will complete in only five seconds.

21)
A timeout argument can be passed to which of the following methods?

1. wait()
2. notify()
3. sleep()
4. join()
5. yield()
6. notifyAll()

Answer:wait(),sleep(),join()

wait(long timeout)-Causes current thread to wait until either another thread invokes the notify()  method orthe notifyAll()  method for this object, or a specified amount of time has elapsed.
join(long millis)-It tellsthe current thread to wait until either the other thread to complete or time has elapsed.
sleep(long millis)-causes the current thread to wait for a specified amount of time.


22)

Which kind of variable would you prefer to synchronize on?

  1. A member variable of a primitive type
  2. A member variable that is an object reference
  3. A method local variable that is a reference to an instance that is created within the method
  4. None of the above
Answer:A member variable that is an object reference

Primitives don't have locks; therefore, they can not be used to synchronize threads. A method local variablethat is a reference to an instance that is created within the method should not be used to synchronize threads,because each thread has its own instance of the object and lock.

23)

Which of the following instance methods should only be called by a thread that holds the lock of the instance on which the method is invoked?

1. join
2. notify
3. notifyAll
4. run
5. wait


Answer:wait(),notify(),notifyAll()
 
wait(),notify(),notifyAll() declared in java.lang.Object should be called within a synchronized block or synchronized function.

24)

Which of the following is a checked exception?

1. IllegalMonitorStateException
2. IllegalThreadStateException
3. IllegalArgumentException
4. InterruptedException
5, None of the above

Answer:InterruptedException
wait(),sleep() and join() have throws clause for java.lang.InterrupedException.So all these functions should put in a try-catch block ,else compile time error .

25)

Which of the following is a true statement? 
  1. The process of executing a synchronized method requires the thread to acquire a lock.
  2. Any overriding method of a synchronized method is implicitly synchronized.
  3. If any method in a class is synchronized, then the class itself must also be declared using the synchronized modifier.
  4. If a thread invokes a static synchronized method on an instance of class A, then the thread must acquire the lock of that instance of class A.
Answer:The process of executing a synchronized method requires the thread to acquire a lock.

The synchronized modifier can not be applied to a class. A method that overrides a synchronized method does not have to be synchronized. If a thread invokes a synchronized instance method on an instance of class A, then the
thread must acquire the lock of that instance of class A. The same is not true for synchronized static methods.A synchronized static method is synchronized on the lock for the Class object that represents the class for which the method is a member.


26)

Which of the following are true statements?

1. program will terminate only when all daemon threads stop running
2. A program will terminate only when all user threads stop running
3. A daemon thread always runs at Thread.MIN_PRIORITY
4. A thread inherits its daemon status from the thread that created it
5. daemon status of a thread can be changed at any time using the  Thread.setDaemon method

Answer:2 & 4

We can set the Daemon status only before starting the thread else it will generate java.lang.IllegalThreadState Exception.We can change the daemon thread priority at any time.

27)
class A extends Thread {
  private int i;
  public void run() {i = 1;}
  public static void main(String[] args) {
    A a = new A(); a.run(); System.out.print(a.i);
}}

What is the result of attempting to compile and run the program?
  1. Prints Nothing
  2. Prints 0 or 1
  3. Prints 0
  4. Prints 1
Answer:Prints 1

The a.run() method was called instead of a.start(); so the entire program runs as a single thread, and a.run() is guaranteed to complete before the print statement is called.

28)

class AnException extends Exception {}
class A extends Thread {
  public void run() throws AnException {
    System.out.print("A"); throw new AnException();
}}
class B {
  public static void main (String[] args) {
    A a = new A(); a.start(); System.out.print("B");
}}

What is the result of attempting to compile and run the program?
  1. Prints A
  2. Prints B
  3. Prints AB
  4. Compile-time error
Answer:Compile-time error

The Runnable.run method does not have a throws clause; so any implementation of run can not throw a checked exception.

29)


class A extends Thread {  String[] sa;
  public A(String[] sa) {this.sa = sa;}
  public void run() {synchronized (sa) {System.out.print(sa[0] + sa[1] + sa[2]);}}}
class B {  private static String[] sa = new String[]{"X","Y","Z"};
  public static void main (String[] args) {
    synchronized (sa) {Thread t1 = new A(sa); t1.start();
      sa[0] = "A"; sa[1] = "B"; sa[2] = "C";
}}}

What is the result of attempting to compile and run the program?
  1. Prints ABC
  2. Prints XYZ
  3. Compile-time error
  4. Run-time error
Answer:Prints ABC

The block inside the main method is synchronized on the String array object sa. Inside the block, a new thread t1 is started and will run at the discretion of the thread scheduler. The A.run method also contains a block that is synchronized on the String array object sa. Thread t1 will continue to block until the synchronized block in the B.main method runs to completion. At that time, the contents of the String array object have all been updated.  

30)

class A extends Thread {
  public void run() {System.out.print("A");}
}
class B {
  public static void main (String[] args) {
    A a = new A();
    a.start();
    a.start();  // 1
  }
}
What is the result of attempting to compile and run the program?
  1. The program compiles and runs without error
  2. The second attempt to start thread t1 is successful
  3. Compile-time error at marker 1
  4. An IllegalThreadStateException is thrown at run-time
Answer: An IllegalThreadStateException is thrown at run-time

Invoking the start method on a thread that has already been started will generate an IllegalThreadStateException.

31)

Which of the following is used to force each thread to reconcile its working copy of a variable with the master copy in main memory?
  1. synchronized
  2. transient
  3. volatile
  4. native
Answer :volatile

A field might be shared between two or more threads. Each thread is allowed to maintain a working copy of the field. If the threads do not reconcile the working copies then each might be working with a different value.The volatile modifier is used to force each thread to reconcile its working copy of the field with the master copy in main memory.  

No comments:

Post a Comment