Here are 10 essential multiple-choice questions on Java Thread Methods and Daemon Threads, covering key concepts.
Question 1
Which method is used to set the name of a thread in Java?
setName()
setThreadName()
setThread()
assignName()
Question 2
What will be the output of the following code?
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.setName("CustomThread");
t1.start();
}
}
Thread-0
MyThread
CustomThread
Compilation Error
Question 3
What is the key difference between start() and run() in Java threads?
start() creates a new thread, but run() executes in the current thread
Both methods create a new thread
run() is an internal method that should not be called
start() directly calls run() without creating a new thread
Question 4
What will happen if start() is called twice on the same thread?
The thread runs twice
A new thread is created each time
It throws an IllegalThreadStateException
It runs normally without any issues
Question 5
What is the effect of Thread.sleep(5000) inside a thread?
The thread is terminated
The thread is paused for 5 seconds but remains in the RUNNABLE state
The thread is paused for 5 seconds and enters the TIMED_WAITING state
The thread releases its lock and resumes immediately
Question 6
What will be the output of this program?
class TestThread extends Thread {
public void run() {
try {
Thread.sleep(1000);
System.out.println("Thread Running");
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
public static void main(String[] args) {
TestThread t = new TestThread();
t.start();
t.interrupt();
}
}
Thread Running
Interrupted
No Output
Both A and B, depending on timing
Question 7
Which of the following is true about a daemon thread in Java?
A daemon thread runs in the background and stops when all user threads finish execution
A daemon thread continues running even if all user threads finish
A daemon thread must be manually stopped
The JVM waits for daemon threads to finish before terminating
Question 8
What happens when setDaemon(true) is called after start()?
The thread becomes a daemon thread
Compilation error
Runtime exception (IllegalThreadStateException)
No effect
Question 9
How can you check if a thread is a daemon thread?
Using isDaemon() method
Using isDaemonThread() method
Using isBackgroundThread() method
Using getThreadType() method
Question 10
Which of the following correctly creates and starts a daemon thread?
Thread t = new Thread(() -> System.out.println("Daemon Running"));
t.start();
t.setDaemon(true);
Thread t = new Thread(() -> System.out.println("Daemon Running"));
t.setDaemon(true);
t.start();
Thread t = new Thread(() -> System.out.println("Daemon Running"));
t.setDaemon(false);
t.start();
None of the above
There are 10 questions to complete.