Examveda
Examveda

Predict the output:
public class Test extends Thread{
      private int i;
      public void run(){
            i++;
      }

      public static void main(String[] args){
            Test a = new Test();
            a.run();
            System.out.print(a.i);
            a.start();
            System.out.print(a.i);
      }
}

A. Prints

B. Prints

C. Prints

D. Compiler error

E. IllegalThreadStateException is thrown

Answer: Option C

Solution(By Examveda Team)

Here, firstly the run() method of the object referred by a is directly invoked. When the run() method of a thread is invoked instead of the start() method, it is executed by the same thread as a conventional method. So it increments i to 1, now the output is 1. After this, the invocation of the start() method schedules a new thread of execution.

Now it is impossible to predict whether the new thread will run first or the second print statement will be executed by the main thread first. So the result of the second print statement can be 1 or 2 depending on the scheduling of the 2 threads.


This Question Belongs to Java Program >> Threads

Join The Discussion

Comments ( 1 )

  1. Pradnya Date
    Pradnya Date :
    6 years ago

    In statement a.i,

    How we can access private member 'i' with his object a??

Related Questions on Threads

What is a thread in Java?

A. A lightweight process that runs independently within a program

B. A data structure to store variables

C. A type of loop

D. A synchronization mechanism