Threads(Java Program ) Questions and Answers
Explanation:-
Answer: Option D. -> The program compiles and runs and displays test.Explanation:-
Answer: Option A. -> run-test run-testt.run() Legal, but does not start a new thread , it is like a method call of a class Test BUT t.start() creates a thread and call run() method.
Explanation:-
Answer: Option D. -> Compilation succeed but Runtime ExceptionOnce a thread has been started, it can never be started again. 2nd time t.start() throws java.lang.IllegalThreadStateException.
Explanation:-
Answer: Option D. -> Clean compile but no output at runtime
Question 7. What will be the output after compiling and executing the following code?
public class Test implements Runnable{
public static void main(String[] args) throws InterruptedException{
Thread a = new Thread(new Test());
a.start();
System.out.print("Begin");
a.join();
System.out.print("End");
}
public void run(){
System.out.print("Run");
}
}
public class Test implements Runnable{
public static void main(String[] args) throws InterruptedException{
Thread a = new Thread(new Test());
a.start();
System.out.print("Begin");
a.join();
System.out.print("End");
}
public void run(){
System.out.print("Run");
}
}
Explanation:-
Answer: Option C. -> "BeginRunEnd" is printed.
Question 8. What is the output for the below code ?
class A implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
1. public class Test{
2. public static void main(String... args){
3. A a = new A();
4. Thread t = new Thread(a);
5. t.setName("good");
6. t.start();
7. }
8. }
class A implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
1. public class Test{
2. public static void main(String... args){
3. A a = new A();
4. Thread t = new Thread(a);
5. t.setName("good");
6. t.start();
7. }
8. }
Explanation:-
Answer: Option A. -> goodThread.currentThread().getName() return name of the current thread.
Explanation:-
Answer: Option C. -> PrintsHere, 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.