Java Multithreading Interview Questions and Answers
Ques 11. Explain the significance of the volatile keyword in Java.
The volatile keyword in Java is used to indicate that a variable's value may be changed by multiple threads simultaneously.
Example:
volatile int sharedVariable = 0;
Ques 12. What is a daemon thread in Java?
A daemon thread is a background thread that runs intermittently and is terminated when all non-daemon threads have completed.
Example:
Thread daemonThread = new Thread(() -> {
/* Daemon thread logic */ });
daemonThread.setDaemon(true);
Ques 13. How does the join() method work in Java?
The join() method is used to wait for a thread to die. It causes the current thread to pause execution until the specified thread completes its execution.
Example:
Thread anotherThread = new Thread(() -> {
/* Thread logic */ });
anotherThread.start();
anotherThread.join();
Ques 14. What is the purpose of the interrupt() method?
The interrupt() method is used to interrupt the execution of a thread. It sets the interrupted flag, causing the thread to stop if it's in a sleeping or waiting state.
Example:
Thread myThread = new Thread(() -> {
while (!Thread.interrupted()) {
/* Thread logic */
}
});
myThread.start();
myThread.interrupt();
Ques 15. Explain the concept of a race condition.
A race condition occurs when two or more threads access shared data concurrently, and the final outcome depends on the order of execution.
Example:
When two threads increment a shared counter without proper synchronization.
Most helpful rated by users: