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. 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.
Join The Discussion
Comments ( 1 )
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
Which interface is used to create a thread in Java?
A. Processor
B. Executor
C. Threadable
D. Runnable
What is the main advantage of using multithreading in Java programs?
A. Reduced memory usage
B. Simplicity of code
C. Improved program performance by utilizing multiple CPUs or CPU cores
D. Elimination of exceptions
How can you create a new thread in Java by implementing the Runnable interface?
A. Create an object of the Thread class
B. Create a class that implements the Runnable interface and override the run() method
C. Use the start() method of the main thread
D. Create an object of the Thread class
In statement a.i,
How we can access private member 'i' with his object a??