<%@ include file="../../ga4.jsp" %> Creating | Starting Java Thread - Quiz Explanation

Creating | Starting Java Thread - Quiz Explanation

The answers you selected are indicated below, along with text that explains the correct answers.
 
1. The following code will successfully create and start a new thread
Please select the best answer.
  A. Thread t = new Thread();
  B. Thread t = new Thread();
t.run();
  C. Thread t = new Thread();
t.start();
  D. None of the above.
  The correct answer is C. Both answers A and B create a new Thread instance. But to start the thread, you need to invoke start(), which in turn invokes run().

2. To write a thread class that will do something useful, you should
Please select the best answer.
  A. Make sure to start it
  B. Create a subclass of a thread
  C. Supply a run() method for the thread
  D. None of the above.
  The correct answer is C. You must supply a run() method for the thread. You can do this by subclassing the Thread class, and you also have to provide behavior for the run() method that you create.

3. What will the following code print when run?
public class RunTest {
  public static volatile int counter = 0;
  static class RunnerDec implements Runnable{
    public void run(){
      for(int i=0;i < 5000; i++){
        counter--;
      }
    }
  }
  static class RunnerInc implements Runnable{
    public void run(){
      for(int i=0;i <5000; i++){
        counter++;
      }
    }
  }
  public static void main(String[] args) {
    RunnerDec rd = new RunnerDec();
    RunnerInc ri = new RunnerInc();
    Thread t1 = new Thread(rd);
    Thread t2 = new Thread(ri);
    t1.start();
    t2.start();
    try{
      t1.join();
      t2.join();
    }catch(Exception e){
        e.printStackTrace();
    }
    System.out.println(counter);
  }
} 
Select 1 option: Please select the best answer.
  A. It will always print 0.
  B. It may print any number between -5000 to 5000.
  C. It may print any number between -5000 to 5000 except 0.
  D. The program will keep running for ever.
  The correct answer is B. Making the variable counter volatile only ensures that if it is updated by one thread, another thread will see the updated value. However, it still does not ensure that the increment and decrement operations will be done atomically. Thus, it is possible that while one thread is performing counter++, another thread corrupts the value by doing counter--. Because of this corruption, it is not possible to determine the final value of counter.