Java MCQ
JAVA TRICKY multithreading MCQ
What is the output of: class Test extends Thread { public void run() { System.out.print("Running"); } } public static void main(String[] args) { Test t = new Test(); t.start(); t.run(); }
t.start() starts a new thread, and t.run() calls the method directly in main thread - both execute.
What is the output of: class Test implements Runnable { public void run() { System.out.print(Thread.currentThread().getName()); } } public static void main(String[] args) { Thread t = new Thread(new Test()); t.run(); }
Calling run() directly executes in current thread (main), not in a new thread. Use start() for new thread.
What is the output of: class Test extends Thread { public void run() { System.out.print("Running"); } } public static void main(String[] args) { Test t = new Test(); t.start(); t.start(); }
A thread cannot be started more than once. Second start() call throws IllegalThreadStateException.
What is the output of: class Test { public static void main(String[] args) { System.out.print(Thread.currentThread().getPriority()); } }
Main thread has default priority of 5 (NORM_PRIORITY). Thread priorities range from 1 to 10.
What is the output of: class Test { int count = 0; void increment() { count++; } } Two threads call increment() 1000 times each. What is the possible value of count?
Due to race condition, count++ is not atomic. Some increments may be lost, so final value ≤ 2000.
What is the output of: synchronized void method1() { // code } void method2() { synchronized(this) { // same code } } Are these equivalent?
synchronized method and synchronized(this) both use the current object as lock monitor.
What happens when: Thread t = new Thread(); t.start(); t.start();
A thread cannot be restarted once it has completed execution. Second start() throws exception.
What is the output of: class Test extends Thread { public void run() { try { Thread.sleep(1000); } catch(Exception e) {} System.out.print("End"); } } t.start(); System.out.print("Start");
Main thread prints "Start" immediately, while new thread sleeps for 1 second then prints "End".
What is true about wait(), notify(), notifyAll()?
wait(), notify(), notifyAll() must be called from synchronized block/method, otherwise throw IllegalMonitorStateException.
What is the difference between sleep() and wait()?
sleep() keeps the lock, wait() releases the lock and waits for notify()/notifyAll().