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);
}
}
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. Run time error
B. Compiler error
C. Prints
D. 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.
In statement a.i,
How we can access private member 'i' with his object a??