Introduction to Java Programming, Sixth Edition, Y. Daniel Liang

Chapter 24 Multithreading


Section 24.3 Creating Tasks and Threads
1  Analyze the following code:

public class Test implements Runnable {
   public static void main(String[] args) {
     Thread t = new Thread(this);
     t.start();
   }

   public void run() {
     System.out.println("test");
   }
}

A. The program does not compile because this cannot be referenced in a static method.
B. The program compiles fine, but it does not print anything because t does not invoke the run() method.
C. The program compiles and runs fine and displays test on the console.
D. None of the above.

2  What is the output of the following code?

// Test.java: Define threads using the Thread class
public class Test {
   /** Main method */
   public static void main(String[] args) {
     new Test();
   }

   public Test() {
     // Create threads
     PrintChar printA = new PrintChar('a', 4);
     PrintChar printB = new PrintChar('b', 4);

     // Start threads
     printA.run();
     printB.run();
   }

   class PrintChar implements Runnable {
     private char charToPrint; // The character to print
     private int times; // The times to repeat

     /** Construct a thread with specified character and number of
        times to print the character
      */
     public PrintChar(char c, int t) {
       charToPrint = c;
       times = t;
     }

     /** Override the run() method to tell the system
        what the thread will do
      */
     public void run() {
       for (int i = 0; i < times; i++)
         System.out.print(charToPrint);
     }
   }
}

A. aaaaabbbbb
B. bbbbbaaaaa
C. ababababab

3  Analyze the following code:

public abstract class Test implements Runnable {
   public void doSomething() {
   };
}

A. The program will not compile because it does not implement the run() method.
B. The program will not compile because it does not contain abstract methods.
C. The program compiles fine.
D. None of the above.

4  Analyze the following code:

public class Test implements Runnable {
   public static void main(String[] args) {
     Test t = new Test();
     t.start();
   }

   public void run() {
   }
}

A. The program does not compile because the start() method is not defined in the Test class.
B. The program compiles, but it does not run because the start() method is not defined.
C. The program compiles, but it does not run because the run() method is not implemented.
D. The program compiles and runs fine.

5  Analyze the following code:

public class Test implements Runnable {
   public static void main(String[] args) {
     Test t = new Test();
   }

   public Test() {
     Thread t = new Thread(this);
     t.start();
   }

   public void run() {
     System.out.println("test");
   }
}

A. The program has a compilation error because t is defined in both the main() method and the constructor Test().
B. The program compiles fine, but it does not run because you cannot use the keyword this in the constructor.
C. The program compiles and runs and displays nothing.
D. The program compiles and runs and displays test.

Section 24.4 The Thread Class
6  Why does the following class have a syntax error?

import java.applet.*;

public class Test extends Applet implements Runnable {
    public void init() throws InterruptedException {
      Thread t = new Thread(this);
       t.sleep(1000);
    }

    public synchronized void run() {
    }
}

A. The sleep() method is not invoked correctly; it should be invoked as Thread.sleep(1000).
B. You cannot put the keyword synchronized in the run() method.
C. The init() method is defined in the Applet class, and it is overridden incorrectly because it cannot claim exceptions in the subclass.
D. The sleep() method should be put in the try-catch block. This is the only reason for the compilation failure.

7  Which of the following expressions must be true if you create a thread using Thread = new Thread(object)?

A. object instanceof Thread
B. object instanceof Frame
C. object instanceof Applet
D. object instanceof Runnable

8  The following methods in the Thread class are deprecated:

A. yield()
B. stop();
C. resume();
D. suspend();

9  You can use the _________ method to temporarily release time for other threads.

A. sleep(long milliseconds)
B. yield()
C. stop()
D. suspend()

10  Which of the following statements are defined in the Object class?

A. sleep(long milliseconds)
B. wait()
C. notify()
D. notifyAll()
E. toString()

11  You can use the ________ method to force one thread to wait for another thread to finish.

A. sleep(long milliseconds)
B. yield()
C. stop()
D. suspend()
E. join()

12  When you run the following program, what will happen?

public class Test extends Thread {
   public static void main(String[] args) {
     Test t = new Test();
     t.start();
     t.start();
   }

   public void run() {
     System.out.println("test");
   }
}

A. Nothing is displayed.
B. The program displays test twice.
C. The program displays test once.
D. An illegal java.lang.IllegalThreadStateException may be thrown because you just started thread and thread might have not yet finished before you start it again.

13  Which of the following method is a static in java.lang.Thread?

A. run()
B. sleep(long)
C. start()
D. join()
E. setPriority(int)

14  Which of the following methods in Thread throws InterruptedException?

A. run()
B. sleep(long)
C. start()
D. yield()
E. setPriority(int)

15  Given the following code, which set of code can be used to replace the comment so that the program displays time to the console every second?

import java.applet.*;
import java.util.*;

public class Test extends Applet implements Runnable {
   public void init() {
     Thread t = new Thread(this);
     t.start();
   }

   public void run() {
     for(; ;) {
       //display time every second
       System.out.println(new Date().toString());
     }
   }
}

A. try { sleep(1000); } catch(InterruptedException e) { }
B. try { t.sleep(1000); } catch(InterruptedException e) { }
C. try { Thread.sleep(1000); } catch(RuntimeException e) { }
D. try { Thread.sleep(1000); } catch(InterruptedException e) { }

Section 24.5 Example: Flashing Text
16  Which of the following statements are true?

A. You can use a timer or a thread to control animation.
B. A timer is a source component that fires an ActionEvent at a ?fixed rate.?
C. The timer and event-handling run on the same event dispatcher thread. If it takes a long time to handle the event, the actual delay time between two events will be longer than the requested delay time.
D. In general, threads are more reliable and responsive than timers.

Section 24.6 GUI Event Dispatcher Thread
17  Which of the following statements are true?

A. The javax.swing.SwingUtilities.invokeLater method creates a thread.
B. The javax.swing.SwingUtilities.invokeAndWait method runs the code in the event dispatcher thread.
C. The javax.swing.SwingUtilities.invokeLater method runs the code in the event dispatcher thread and doesn't return until the event-dispatching thread has executed the specified code.
D. GUI event handling are executed in the event dispatcher thread.

Section 24.8 Thread Pools
18  Suppose there are three Runnable tasks, task1, task2, task3. How do you run them in a thread pool with 2 fixed threads?

A. new Thread(task1).start(); new Thread(task2).start(); new Thread(task3).start();
B. ExecutorService executor = Executors.newFixedThreadPool(3); executor.execute(task1); executor.execute(task2); executor.execute(task3);
C. ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(task1); executor.execute(task2); executor.execute(task3);
D. ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(task1); executor.execute(task2); executor.execute(task3);

19  How do you create a cashed thread pool?

A. ExecutorService executor = Executors.newCachedThreadPool();
B. ExecutorService executor = Executors.newCachedThreadPool(1);
C. ExecutorService executor = Executors.newCachedThreadPool(2);
D. ExecutorService executor = Executors.newCachedThreadPool(3);

Section 24.9 Thread Synchronization
20  The keyword to synchronize methods in Java is __________.

A. synchronize
B. synchronizing
C. synchronized
D. Synchronized

21  Which of the following statements are true?

A. A synchronized instance method acquires a lock on the object for which the method was invoked.
B. A synchronized instance method acquires a lock on the class of the object for which the method was invoked.
C. A synchronized statement can be used to acquire a lock on any object, not just this object, when executing a block of the code in a method.
D. A synchronized statement is placed inside a synchronized block.

Section 24.10 (Optional) Synchronization Using Locks
22  Which of the following are correct statements to create a Lock?

A. Lock lock = new Lock();
B. Lock lock = new ReentrantLock();
C. Lock lock = new ReentrantLock(true);
D. Lock lock = new ReentrantLock(false);

23  Which of the following are correct statements to create a Lock so the longest-wait thread will obtain the lock first?

A. Lock lock = new Lock();
B. Lock lock = new ReentrantLock();
C. Lock lock = new ReentrantLock(true);
D. Lock lock = new ReentrantLock(false);

24  You should always invoke the unlock method in the finally clause.

A. true
B. false

Section 24.11 (Optional) Cooperation Among Threads
25  How do you create a condition on a lock?

A. Condition condition = lock.getCondition();
B. Condition condition = lock.newCondition();
C. Condition condition = Lock.newCondition();
D. Condition condition = Lock.getCondition();

26  Which method on a condition should you invoke to causes the current thread to wait until the condition is signaled?

A. condition.await();
B. condition.wait();
C. condition.waiting();
D. condition.waited();

27  Which method on a condition should you invoke to wake all waiting threads.

A. condition.wake();
B. condition.signal();
C. condition.wakeAll();
D. condition.signalAll();

28  Which of the following statements are true?

A. A condition is associated with a lock.
B. To invoke methods on a condition, the lock must be obtained first.
C. Once you invoke the await method on a condition, the lock is automatically released. Once the condition is right, the thread re-acquires the lock and continues executing.
D. The signal method on a condition causes the lock for the condition to be released.

Section 24.11.1 (Optional) Java?s built-in monitor
29  Which of the following statements are true?

A. The wait(), notify(), and notifyAll() methods must be invoked from a synchronized method or a synchronized block.
B. When wait() is invoked, it pauses the thread and releases the lock on the object simultaneously. When the thread is restarted after being notified, the lock is automatically reacquired.
C. The notify() method can wake only one waiting thread.
D. An exception would occur if no thread is waiting on the object when the notify() method is invoked on the object.

30  Analyze the following code.

// Test.java: Define threads using the Thread class
import java.util.*;

public class Test {
   private Stack stack = new Stack();
   private int i = 0;

   /** Main method */
   public static void main(String[] args) {
     new Test();
   }

   public Test() {
     // Start threads
     new Producer().start();
     new Consumer().start();
   }

   class Producer extends Thread {
     public void run() {
       while (true) {
           System.out.println("Producer: put " + i);
           stack.push(new Integer(i++));
           synchronized (stack) {
             notifyAll();
           }
       }
     }
   }

   class Consumer extends Thread {
     public void run() {
       while (true) {
         synchronized (stack) {
           try {
             while (stack.isEmpty())
               stack.wait();
             System.out.println("Consumer: get " + stack.pop());
           }
           catch (InterruptedException ex) {
             ex.printStackTrace();
           }
         }
       }
     }
   }
}

A. The program creates two threads: one to add data to the stack and the other to get data from the stack.
B. The program has a compilation error on the notifyAll() method in the Producer class because it is not invoked from the stack object.
C. The program will throw an exception because the notifyAll() method in the Producer class is not invoked from the stack object.
D. The program has a logic error because the lock obtained by the synchronized block for notifyAll in the Producer class is stack and it should be this (i.e., synchronized (this) { notifyAll(); }).

Section 24.13 (Optional) Blocking Queues
31  You can create a blocking queue using _____________.

A. ArrayBlockingQueue
B. LinkedBlockingQueue
C. PriorityBlockingQueue
D. PriorityQueue

32  Which of the following statements are true?

A. a blocking queue has a capacity.
B. A blocking queue causes a thread to block when you try to add an element to a full queue.
C. A blocking queue causes a thread to block when you try to remove an element from an empty queue.
D. The BlockingQueue interface is the base interface for all concrete blocking queue classes.
E. The BlockingQueue interface provides the synchronized put and take methods for adding an element to the head of the queue and for removing an element from the tail of the queue,

Section 24.14 (Optional) Semaphores
33  Which of the following statements are true?

A. Semaphores can be used to restrict the number of threads that access a shared resource.
B. Before accessing the resource, a thread must acquire a permit from the semaphore.
C. After finishing with the resource, the thread must return the permit back to the semaphore.
D. You can create a Semaphore with a specified number of permits.

34  Which of the following methods can be used to obtain a permit from a Semaphore s?

A. get()
B. ask()
C. acquire()
D. delete()

35  Which of the following methods can be used to return a permit to a Semaphore s?
A. return()
B. release()
C. send()
D. add()