Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 9. Threads > Self Test

Self Test

The following questions will help you measure your understanding of the material presented in this chapter. If you have a rough time with some of these at first, don’t beat yourself up. Some of these questions are long and intricate, expect long and intricate questions on the real exam too!

1.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?

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

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

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

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

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

2.Given:
 3.  class MyThread extends Thread {
 4.     public static void main(String [] args) {
 5.        MyThread t = new MyThread();
 6.        Thread x = new Thread(t);
 7.        x.start();
 8.     }
 9.     public void run() {
10.        for(int i=0;i<3;++i) {
11.           System.out.print(i + "..");
12.        }
13.     }
14.  }

What is the result of this code?

  1. Compilation fails

  2. 1..2..3..

  3. 0..1..2..3..

  4. 0..1..2..

  5. An exception occurs at runtime

3.Given:
 3.  class Test {
 4.     public static void main(String [] args) {
 5.        printAll(args);
 6.     }
 7.     public static void printAll(String[] lines) {
 8.        for(int i=0;i<lines.length;i++){
 9.           System.out.println(lines[i]);
10.           Thread.currentThread().sleep(1000);
11.        }
12.     }
13.  }

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

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

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

  3. 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

  4. This code will not compile

  5. Each String in the lines array will print, with at least a one-second pause between lines

4.Assume you have a class that holds two private variables: a and b. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)
  1. public int read(){return a+b;}
    public void set(int a, int b){this.a=a;this.b=b;}

  2. public synchronized int read(){return a+b;}
    public synchronized void set(int a, int b){this.a=a;this.b=b;}

  3. public int read(){synchronized(a){return a+b;}}
    public void set(int a, int b){synchronized(a){this.a=a;this.b=b;}}

  4. public int read(){synchronized(a){return a+b;}}
    public void set(int a, int b){synchronized(b){this.a=a;this.b=b;}}

  5. public synchronized(this) int read(){return a+b;}
    public synchronized(this) void set(int a, int b){this.a=a;this.b=b;}

  6. public int read(){synchronized(this){return a+b;}}
    public void set(int a, int b){synchronized(this){this.a=a;this.b=b;}}

5.Given:
 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?

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

  2. 1 2 3

  3. 1 3

  4. 1 2

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

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

6.Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);

After calling this method, when will the thread A become a candidate to get another turn at the CPU?

  1. After object B is notified, or after two seconds

  2. After the lock on B is released, or after two seconds

  3. Two seconds after object B is notified

  4. Two seconds after lock B is released

7.Which are true? (Choose all that apply.)
  1. The notifyAll() method must be called from a synchronized context

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

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

  4. When a thread is waiting as a result of wait(), it releases its lock

  5. The notify() method causes a thread to immediately release its lock

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

8.Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:
public class Logger {
    private StringBuilder contents = new StringBuilder();
    public void log(String message) {
        contents.append(System.currentTimeMillis());
        contents.append(": ");
        contents.append(Thread.currentThread().getName());
        contents.append(message);
        contents.append("\n");
    }
    public String getContents() { return contents.toString(); }
}

How can we ensure that instances of this class can be safely used by multiple threads?

  1. This class is already thread-safe

  2. Replacing StringBuilder with StringBuffer will make this class thread-safe

  3. Synchronize the log() method only

  4. Synchronize the getContents() method only

  5. Synchronize both log() and getContents()

  6. This class cannot be made thread-safe

9.Given:
public static synchronized void main(String[] args) throws
 InterruptedException {
    Thread t = new Thread();
    t.start();
    System.out.print("X");
    t.wait(10000);
    System.out.print("Y");
}

What is the result of this code?

  1. It prints X and exits

  2. It prints X and never exits

  3. It prints XY and exits almost immeditately

  4. It prints XY with a 10-second delay between X and Y

  5. It prints XY with a 10000-second delay between X and Y

  6. The code does not compile

  7. An exception is thrown at runtime

10.Given:
class MyThread extends Thread {
   MyThread() {
     System.out.print(" MyThread");
   }
   public void run() {
     System.out.print(" bar");
   }
   public void run(String s) {
      System.out.print(" baz");
   }
}
public class TestThreads {
  public static void main (String [] args) {
    Thread t = new MyThread() {
      public void run() {
        System.out.print(" foo");
      }
    };
    t.start();
} }

What is the result?

  1. foo

  2. MyThread foo

  3. MyThread bar

  4. foo bar

  5. foo bar baz

  6. bar foo

  7. Compilation fails

  8. An exception is thrown at runtime

11.Given:
public class ThreadDemo {
    synchronized void a() { actBusy(); }
    static synchronized void b() { actBusy(); }
    static void actBusy() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
    }
    public static void main(String[] args) {
        final ThreadDemo x = new ThreadDemo();
        final ThreadDemo y = new ThreadDemo();
        Runnable runnable = new Runnable() {
            public void run() {
                int option = (int) (Math.random() * 4);
                switch (option) {
                    case 0: x.a(); break;
                    case 1: x.b(); break;
                    case 2: y.a(); break;
                    case 3: y.b(); break;
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}

					  

Which of the following pairs of method invocations could NEVER be executing at the same time? (Choose all that apply.)

  1. x.a() in thread1, and x.a() in thread2

  2. x.a() in thread1, and x.b() in thread2

  3. x.a() in thread1, and y.a() in thread2

  4. x.a() in thread1, and y.b() in thread2

  5. x.b() in thread1, and x.a() in thread2

  6. x.b() in thread1, and x.b() in thread2

  7. x.b() in thread1, and y.a() in thread2

  8. x.b() in thread1, and y.b() in thread2

12.Given:
public class TwoThreads {
    static Thread laurel, hardy;
    public static void main(String[] args) {
        laurel = new Thread() {
            public void run() {
                System.out.println("A");
                try {
                    hardy.sleep(1000);
                } catch (Exception e) {
                    System.out.println("B");
                }
                System.out.println("C");
            }
        };
        hardy = new Thread() {
            public void run() {
                System.out.println("D");
                try {
                    laurel.wait();
                } catch (Exception e) {
                    System.out.println("E");
                }
                System.out.println("F");
            }
        };
        laurel.start();
        hardy.start();
    }
}

					  

Which letters will eventually appear somewhere in the output? (Choose all that apply.)

  1. A

  2. B

  3. C

  4. D

  5. E

  6. F

  7. The answer cannot be reliably determined

  8. The code does not compile

13.Given:
 3. public class Starter implements Runnable {
 4.   void go(long id) {
 5.     System.out.println(id);
 6.   }
 7.   public static void main(String[] args) {
 8.     System.out.print(Thread.currentThread().getId() + " ");
 9.     // insert code here
10.   }
11.   public void run() { go(Thread.currentThread().getId()); }
12. }

And given the following five fragments:

I.   new Starter().run();
II.  new Starter().start();
III. new Thread(new Starter());
IV.  new Thread(new Starter()).run();
V.   new Thread(new Starter()).start();

When the five fragments are inserted, one at a time at line 9, which are true? (Choose all that apply.)

  1. All five will compile

  2. Only one might produce the output 4 4

  3. Only one might produce the output 4 2

  4. Exactly two might produce the output 4 4

  5. Exactly two might produce the output 4 2

  6. Exactly three might produce the output 4 4

  7. Exactly three might produce the output 4 2

14.Given:
 3. public class Leader implements Runnable {
 4.   public static void main(String[] args) {
 5.     Thread t = new Thread(new Leader());
 6.     t.start();
 7.     System.out.print("m1 ");
 8.     t.join();
 9.     System.out.print("m2 ");
10.   }
11.   public void run() {
12.     System.out.print("r1 ");
13.     System.out.print("r2 ");
14.   }
15. }

Which are true? (Choose all that apply.)

  1. Compilation fails

  2. The output could be r1 r2 m1 m2

  3. The output could be m1 m2 r1 r2

  4. The output could be m1 r1 r2 m2

  5. The output could be m1 r1 m2 r2

  6. An exception is thrown at runtime

15.Given:
 3. class Dudes {
 4.   static long flag = 0;
 5.   // insert code here
 6.     if(flag == 0) flag = id;
 7.     for(int x = 1; x < 3; x++) {
 8.       if(flag == id) System.out.print("yo ");
 9.       else System.out.print("dude ");
10.     }
11.   }
12. }
13. public class DudesChat implements Runnable {
14.   static Dudes d;
15.   public static void main(String[] args) {
16.     new DudesChat().go();
17.   }
18.   void go() {
19.     d = new Dudes();
20.     new Thread(new DudesChat()).start();
21.     new Thread(new DudesChat()).start();
22.   }
23.   public void run() {
24.     d.chat(Thread.currentThread().getId());
25.   }
26. }

					  

And given these two fragments:

I.  synchronized void chat(long id) {
II. void chat(long id) {

When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)

  1. An exception is thrown at runtime

  2. With fragment I, compilation fails

  3. With fragment II, compilation fails

  4. With fragment I, the output could be yo dude dude yo

  5. With fragment I, the output could be dude dude yo yo

  6. With fragment II, the output could be yo dude dude yo

16.Given:
 3. class Chicks {
 4.   synchronized void yack(long id) {
 5.     for(int x = 1; x < 3; x++) {
 6.       System.out.print(id + " ");
 7.       Thread.yield();
 8.     }
 9.   }
10. }
11. public class ChicksYack implements Runnable {
12.   Chicks c;
13.   public static void main(String[] args) {
14.     new ChicksYack().go();
15.   }
16.   void go() {
17.     c = new Chicks();
18.     new Thread(new ChicksYack()).start();
19.     new Thread(new ChicksYack()).start();
20.   }
21.   public void run() {
22.     c.yack(Thread.currentThread().getId());
23.   }
24. }

					  

Which are true? (Choose all that apply.)

  1. Compilation fails

  2. The output could be 4 4 2 3

  3. The output could be 4 4 2 2

  4. The output could be 4 4 4 2

  5. The output could be 2 2 4 4

  6. An exception is thrown at runtime

17.Given:
 3. public class Chess implements Runnable {
 4.   public void run() {
 5.     move(Thread.currentThread().getId());
 6.   }
 7.   // insert code here
 8.     System.out.print(id + " ");
 9.     System.out.print(id + " ");
10.   }
11.   public static void main(String[] args) {
12.     Chess ch = new Chess();
13.     new Thread(ch).start();
14.     new Thread(new Chess()).start();
15.   }
16. }

And given these two fragments:

I.  synchronized void move(long id) {
II. void move(long id) {

When either fragment I or fragment II is inserted at line 7, which are true? (Choose all that apply.)

  1. Compilation fails

  2. With fragment I, an exception is thrown

  3. With fragment I, the output could be 4 2 4 2

  4. With fragment I, the output could be 4 4 2 3

  5. With fragment II, the output could be 2 4 2 4


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint