Wednesday, October 26, 2011

Java Interview questions part-4 (Multi Threading)





Q1.       Click the Exhibit button.               What is the result?






            A. The code will deadlock.

            B. The code may run with no output.

            C. An exception is thrown at runtime.

            D. The code may run with output "0 6".

            E. The code may run with output "2 0 6 4".

            F. The code may run with output "0 2 4 6".



Q2.       Given:



            public class Threads2 implements Runnable {

                        public void run() {

                                    System.out.println("run.");

                                    throw new RuntimeException("Problem");

                        }

                        public static void main(String[] args) {

                                    Thread t = new Thread(new Threads2());

                                    t.start();

                                    System.out.println("End of method.");

                        }

            }          



            Which two can be results? (Choose two.)



            A.         java.lang.RuntimeException: Problem

            B.         run.

                        java.lang.RuntimeException: Problem

            C.         End of method.

                        java.lang.RuntimeException: Problem

            D.         End of method.

                        run.

                        java.lang.RuntimeException: Problem

            E.         run.

                        java.lang.RuntimeException: Problem

                        End of method.



Q3.       Given:



            public class TestSeven extends Thread {

                        private static int x;



                        public synchronized void doThings() {

                                    int current = x;

                                    current++;

                                    x = current;

                        }

                        public void run() {

                                    doThings();

                        }

            }



            Which statement is true?



            A.    Compilation fails.

            B.    An exception is thrown at runtime.

            C.    Synchronizing the run() method would make the class thread-safe.

            D.    The data in variable "x" are protected from concurrent access problems.

            E.    Declaring the doThings() method as static would make the class thread-safe.

            F.    Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the          class thread-safe.



Q4.       Given:25



            public class Threads3 implements Runnable {

                        public void run() {

                                    System.out.print("running");

                        }



                        public static void main(String[] args) {

                                    Thread t = new Thread(new Threads3());

                                    t.run();

                                    t.run();

                                    t.start();

                        }

            }



            What is the result?

                       

            A.   Compilation fails.

            B.   An exception is thrown at runtime.

            C.   The code executes and prints "running".

            D.   The code executes and prints "runningrunning".

            E.   The code executes and prints "runningrunningrunning".



Q5.       Given:



            public class NamedCounter{

                        private final String name;

                        private int count;



                        public NamedCounter(String name) { this.name = name; }

                        public String getName() { return name; }

                        public void increment() { count++; }

                        public int getCount() { return count; }

                        public void reset() { count = 0; }

            }



            Which three changes should be made to adapt this class to be used safely by multiple threads?(Choose        three.)



            A.   declare reset() using the synchronized keyword

            B.   declare getName() using the synchronized keyword

            C.   declare getCount() using the synchronized keyword

            D.   declare the constructor using the synchronized keyword

            E.   declare increment() using the synchronized keyword



Q6.       Given:



            void waitForSignal() {



            Object obj = new Object();



            synchronized (Thread.currentThread()) {

                        obj.wait();

                        obj.notify();

            }

                       

            Which statement is true?



            A.   This code may throw an InterruptedException.

            B.   This code may throw an IllegalStateException.

            C.   This code may throw a TimeoutException after ten minutes.

            D.   This code will not compile unless "obj.wait()" is replaced with "((Thread) obj).wait()".

            E.   Reversing the order of obj.wait() and obj.notify() may cause this method to complete normally.

            F.   A call to notify()or notifyAll() from another thread may cause this method to complete normally.                                  



Q7.       Which two code fragments will execute the method doStuff() in a separate thread? (Choose two.)



            A.         new Thread() {

                                    public void run() { doStuff(); }

                        };

            B.         new Thread() {

                                    public void start() { doStuff(); }

                        };

            C.         new Thread() {

                                    public void start() { doStuff(); }

                        }.run();

            D.         new Thread() {

                                     public void run() { doStuff(); }

                        }.start();

            E.         new Thread(new Runnable() {

                                    public void run() { doStuff(); }

                         }).run();

            F.         new Thread(new Runnable() {

                                    public void run() { doStuff(); }

                         }).start();



Q8.       Given:



            public class TestOne implements Runnable {



                        public static void main (String[] args) throws Exception {



                                    Thread t = new Thread(new TestOne());

                                    t.start();

                                    System.out.print("Started");

                                    t.join();

                                    System.out.print("Complete");

                        }



                        public void run() {

                                    for (int i = 0; i < 4; i++) {

                                                System.out.print(i);

                                    }

                        }

            }



            What can be a result?

                       

            A.   Compilation fails.

            B.   An exception is thrown at runtime.

            C.   The code executes and prints "StartedComplete".

            D.   The code executes and prints "StartedComplete0123".

            E.   The code executes and prints "Started0123Complete".



Q9.       Given:



            public class TestOne {

                        public static void main (String[] args) throws Exception {

                                    Thread.sleep(3000);

                                    System.out.println("sleep");

                        }

            }



            What is the result?



            A.   Compilation fails.

            B.   An exception is thrown at runtime.

            C.   The code executes normally and prints "sleep".

            D.   The code executes normally, but nothing is printed.



Q10.     Given:

            public class Test {

                        public enum Dogs {collie, harrier, shepherd};



                        public static void main(String [] args) {

                                    Dogs myDog = Dogs.shepherd;

                                    switch (myDog) {

                                                case collie:        System.out.print("collie ");

                                                case default:      System.out.print("retriever ");

                                                case harrier:      System.out.print("harrier ");

                                    }

                        }

            }



            What is the result?



            A. harrier                                  B. shepherd                               C. retriever

            D. Compilation fails.               E. retriever harrier                     F. An exception is thrown at runtime.



Q11.     Given:



            Runnable r = new Runnable() {

                        public void run() {

                                    System.out.print("Cat");

                        }

            };



            Thread t = new Thread(r) {

                        public void run() {

                                    System.out.print("Dog");

                        }

            };

            t.start();



            What is the result?



            A. Cat                           B. Dog                         C. Compilation fails.        D. The code runs with no output.



            E. An exception is thrown at runtime.



Q12.     Given:



            public class Thread12 {

                        public static void main (String[] args) {

                                    new Thread12().go();

                        }

                        public void go() {

                                    Runnable r = new Runnable() {

                                                public void run() {

                                                            System.out.print("foo");

                                                }

                                    };

                                    Thread t = new Thread(r);

                                    t.start();

                                    t.start();

                        }

            }          



            What is the result?



            A. Compilation fails.                                                 B. An exception is thrown at runtime.



            C. The code executes normally and prints "foo".       D. The code executes normally, but nothing is printed.



Q13.     Given:



            public class Starter extends Thread {

                        private int x = 2;



                        public static void main(String[] args) throws Exception {

                                    new Starter().makeItSo();

                        }



                        public Starter()   {

                                    x = 5;

                                    start();

                        }



                        public void makeItSo() throws Exception  {

                                    join();

                                    x = x - 1;

                                    System.out.println(x);

                        }



                        public void run() {

                                    x *= 2;

                        }

            }



            Click the Exhibit button.   What is the output if the main() method is run?



            A. 4                                          B. 5                                    C. 8



            D. 9                                          E. Compilation fails.               F. An exception is thrown at runtime.



            G. It is impossible to determine for certain.



Q14.     Given:



            foo and bar are public references available to many other threads. foo refers to a Thread and bar is an

            Object. The thread foo is currently executing bar.wait().



            From another thread, what provides the most reliable way to ensure that foo will stop executing wait()?

           

            A. foo.notify();                           B. bar.notify();                           C. foo.notifyAll();



            D. Thread.notify();                     E. bar.notifyAll();                   F. Object.notify();



Q15.     Given:



            1.         public class TestFive {

            2.                     private int x;

            3.                     public void foo() {

            4.                                 int current = x;

            5.                                 x = current + 1;

            6.                     }

            7.                     public void go() {

            8.                                 for(int i = 0; i < 5; i++) {

            9.                                             new Thread() {

            10.                                                        public void run() {

            11.                                                                    foo();

            12.                                                                    System.out.print(x + ", ");

            13.                                                        } }.start();

            14.                    }

            15.        }



            Which two changes, taken together, would guarantee the output: 1, 2, 3, 4, 5, ? (Choose two.)



            A.  move the line 12 print statement into the foo() method

            B.  change line 7 to public synchronized void go() {

            C.  change the variable declaration on line 2 to private volatile int x;

            D.  wrap the code inside the foo() method with a synchronized(this) block

            E.  wrap the for loop code inside the go() method with a synchronized block synchronized(this)

                                                                                                                                    {//for loop code here }

 Q16.    Given:

            public class MyLogger {

                        private StringBuilder logger = new StringBuilder();



                        public void log(String message, String user) {

                                    logger.append(message);

                                    logger.append(user);

                        }

            }



            The programmer must guarantee that a single MyLogger object works properly for a multi-threaded            system. How must this code be changed to be thread-safe?



            A.   synchronize the log method

            B.   replace StringBuilder with StringBuffer

            C.   replace StringBuilder with just a String object and use the string concatenation (+=) within the log                            method

            D.   No change is necessary, the current MyLogger code is already thread-safe.



Q17      Given:



            public class TestSeven extends Thread {

                        private static int x;



                        public synchronized void doThings() {

                                    int current = x;

                                    current++;

                                    x = current;

                        }



                        public void run() {

                                    doThings();

                        }

            }

                       

            Which statement is true?



            A.   Compilation fails.

            B.   An exception is thrown at runtime.

            C.   Synchronizing the run() method would make the class thread-safe.

            D.   The data in variable "x" are protected from concurrent access problems.

            E.   Declaring the doThings() method as static would make the class thread-safe.

            F.   Wrapping the statements within doThings() in a synchronized(new Object()) { } block would make the          class thread-safe.



Q18.     Which two of the following methods are defined in class Thread?



            A.  start()                    B.  wait()                       C.  notify()                   D.  run()                            E.  terminate()



Q19.     The following block of code creates a Thread using a Runnable target:



            Runnable target = new MyRunnable();

            Thread myThread = new Thread(target);



            Which of the following classes can be used to create the target, so that the preceding code compiles             correctly?



            A.   public class MyRunnable extends Runnable{public void run(){}}

            B.   public class MyRunnable extends Object{public void run(){}}

            C.   public class MyRunnable implements Runnable{public void run(){}}

            D.   public class MyRunnable implements Runnable{void run(){}}

            E.   public class MyRunnable implements Runnable{public void start(){}}



Q20.     Given the following,



            class MyThread extends Thread {



                        public static void main(String [] args) {



                                    MyThread t = new MyThread();

                                    t.start();

                                    System.out.print("one. ");

                                    t.start();

                                    System.out.print("two. ");

                        }



                        public void run() {

                                    System.out.print("Thread ");

                        }

            }



            what is the result of this code?



            A.   Compilation fails

            B.   An exception occurs at runtime.

            C.   Thread one. Thread two.

            D.   The output cannot be determined.



Q21.     Given the following,



            class Thread21{



                        public static void main(String [] args) {

                                    printAll(args);

                        }



                        public static void printAll(String[] lines) {



                                    for(int i=0;i<lines.length;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?



            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.



Q22.     Which two are true?



            A.   A static method cannot be synchronized.

            B.   If a class has synchronized code, multiple threads can still access the nonsynchronized code.

            C.   Variables can be protected from concurrent access problems by marking them with the synchronized                       keyword.

            D.   When a thread sleeps, it releases its locks.

            E.   When a thread invokes wait(), it releases its locks.



Q23.     Which three are methods of the Object class? (Choose three.)



            A.  notify();                             B.  notifyAll();                         C.  isInterrupted();

                       

            D.  synchronized();                    E.  interrupt();                           F.  wait(long msecs);



            G.  sleep(long msecs);                H.  yield();



Q24.     Given the following,



            1.    public class WaitTest {

            2.         public static void main(String [] args) {

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

            4.                     synchronized(args){

            5.                                 System.out.print("2 ");

            6.                                 try {

            7.                                             args.wait();

            8.                                 }

            9.                                 catch(InterruptedException e){}

            10.                    }

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

            12.        }

            13.  }



            what is the result of trying to compile and run this program?



            A.   It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 7.

            B.   1 2 3

            C.   1 3

            D.   1 2

            E.   At runtime, it throws an IllegalMonitorStateException when trying to wait.

            F.   It will fail to compile because it has to be synchronized on the this object.



Q25.     Which two are true?



            A.   The notifyAll() method must be called from a synchronized context.

            B.   To call wait(), an object must own the lock on the thread.

            C.   The notify() method is defined in class java.lang.Thread.

            D.   When a thread is waiting as a result of wait(), it release its locks.

            E.   The notify() method causes a thread to immediately release its locks.

            F.   The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless         of the object they’re waiting on.



Q26.     Assume you create a program and one of your threads (called backgroundThread) does some lengthy         numerical processing. What would be the proper way of setting its priority to try to get the rest of the             system to be very responsive while the thread is running? (Choose all that apply.)



            A.   backgroundThread.setPriority(Thread.LOW_PRIORITY);

            B.   backgroundThread.setPriority(Thread.MAX_PRIORITY);

            C.   backgroundThread.setPriority(1);

            D.   backgroundThread.setPriority(Thread.NO_PRIORITY);

            E.   backgroundThread.setPriority(Thread.MIN_PRIORITY);

            F.   backgroundThread.setPriority(Thread.NORM_PRIORITY);

            G.   backgroundThread.setPriority(10);



Q27.     Which two are true?



            A.   Deadlock will not occur if wait()/notify() is used.

            B.   A thread will resume execution as soon as its sleep duration expires.

            C.   Synchronization can prevent two objects from being accessed by the same thread.

            D.   The wait() method is overloaded to accept a duration.

            E.   The notify() method is overloaded to accept a duration.

            F.   Both wait() and notify() must be called from a synchronized context.

            G.   wait() can throw a runtime exception

            H.   sleep() can throw a runtime exception.



Q28.     20. Given the following,



            public class SyncTest {



                        public static void main (String [] args) {



                                    Thread t =  new Thread() {



                                                                        Foo f = new Foo();

                                                                       

                                                                        public void run() {



                                                                                    f.increase(20);

                                                                        }

                                                            };

                                    t.start();

                        }

            }



            class Foo {



                        private int data = 23;



                        public void increase(int amt) {



                                    int x = data;

                                    data = x + amt;

                        }

            }



            and assuming that data must be protected from corruption, what—if anything—can you add to the    preceding code to ensure the integrity of data?



            A.   Synchronize the run method.

            B.   Wrap a synchronize(this) around the call to f.increase().

            C.   The existing code will not compile.

            D.   The existing code will cause a runtime exception.

            E.   Put in a wait() call prior to invoking the increase() method.

            F.   Synchronize the increase() method



Q29.     Which three guarantee that a thread will leave the running state?



            A.   yield()                                 B.   wait()                                C.   notify()                    D.   notifyAll()



            E.   sleep(1000)                                  F.   aLiveThread.join()                        G.   Thread.killThread()



Q30.     Given the following,



            public class MyRunnable implements Runnable {

                        public void run() {

                                    // some code here

                        }

            }

            which of these will create and start this thread?



            A.   new Runnable(MyRunnable).start();

            B.   new Thread(MyRunnable).run();

            C.   new Thread(new MyRunnable()).start();

            D.   new MyRunnable().start();




1 comments:

Naviya Nair said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Vamshi krishnam raju | Bloggerized by Vamshi krishnam raju - Vamshi krishnam raju | Vamshi krishnam raju