1. What is a thread in Java?
Answer: A thread in Java is the smallest unit of execution within a process. It allows concurrent execution of tasks, providing a way to improve program performance.
2. Explain the difference between the Thread class and the Runnable interface.
Answer: The Thread class is a class in Java that directly extends the Thread class, while the Runnable interface is an interface that can be implemented by a class to define a thread. Using Runnable is generally preferred as it allows for better object-oriented design and avoids the single inheritance limitation.
3. How can you create a thread in Java? Provide examples.
Answer: Threads can be created by extending the Thread class or implementing the Runnable interface.
java// Extending Thread class
class MyThread extends Thread {
public void run() {
// Code to be executed in the new thread
}
}
// Implementing Runnable interface
class MyRunnable implements Runnable {
public void run() {
// Code to be executed in the new thread
}
}
// Creating and starting threads
MyThread thread1 = new MyThread();
thread1.start();
Thread thread2 = new Thread(new MyRunnable());
thread2.start();4. What is the synchronized keyword used for?
Answer: The synchronized keyword is used to control access to critical sections of code, ensuring that only one thread can execute the synchronized code block or method at a time, preventing race conditions.
java// Synchronized method
public synchronized void synchronizedMethod() {
// Code that needs to be thread-safe
}
// Synchronized block
public void someMethod() {
synchronized (this) {
// Code that needs to be thread-safe
}
}5. Explain the concept of deadlock. How can it be avoided?
Answer: Deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a resource. Avoiding deadlock involves careful management of locks and their acquisition order.
java// Avoiding deadlock by acquiring locks in a consistent order
public void method1() {
synchronized (lock1) {
synchronized (lock2) {
// Code
}
}
}
public void method2() {
synchronized (lock1) {
synchronized (lock2) {
// Code
}
}
}6. What is the purpose of the volatile keyword?
Answer: The volatile keyword in Java ensures visibility of changes to variables across threads, preventing thread-local caching of variables.
javapublic class SharedResource {
private volatile int sharedVariable;
public void setSharedVariable(int value) {
this.sharedVariable = value;
}
public int getSharedVariable() {
return sharedVariable;
}
}7. Explain the wait(), notify(), and notifyAll() methods.
Answer: These methods are used for inter-thread communication. wait() makes a thread wait until another thread notifies it, and notify() wakes up one of the threads that are waiting. notifyAll() wakes up all waiting threads.
javapublic class SharedResource {
public synchronized void produce() throws InterruptedException {
while (queue.size() == MAX_SIZE) {
wait();
}
// Produce item and notify consumers
notify();
}
public synchronized void consume() throws InterruptedException {
while (queue.isEmpty()) {
wait();
}
// Consume item and notify producers
notify();
}
}8. What is the purpose of the ThreadLocal class?
Answer: The ThreadLocal class in Java provides a way to maintain thread-specific variables. Each thread that accesses the variable sees its own, independently initialized copy.
javapublic class ThreadLocalExample {
private static final ThreadLocal<String> threadLocalVariable = new ThreadLocal<>();
public static void setThreadLocalVariable(String value) {
threadLocalVariable.set(value);
}
public static String getThreadLocalVariable() {
return threadLocalVariable.get();
}
}9. How can you interrupt a running thread in Java?
Answer: The interrupt() method is used to interrupt the execution of a thread.
javaThread myThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// Code
}
});
// Interrupt the thread
myThread.interrupt();10. Explain the concept of thread pooling.
Answer: Thread pooling involves maintaining a pool of worker threads to efficiently execute tasks. It reduces the overhead of creating and destroying threads for each task.
javaExecutorService executorService = Executors.newFixedThreadPool(5);
// Submitting tasks to the thread pool
executorService.submit(() -> {
// Task code
});
// Shutting down the thread pool
executorService.shutdown();11. What is the purpose of the yield() method?
Answer: The yield() method is a hint to the scheduler that the current thread is willing to release its current time slice, allowing other threads to run.
javapublic class YieldExample extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
// Code
Thread.yield();
}
}
}12. How does the join() method work?
Answer: The join() method is used to wait for a thread to die. It blocks the current thread until the thread on which it is called completes its execution.
javaThread thread = new Thread(() -> {
// Code
});
// Start the thread
thread.start();
// Wait for the thread to finish
thread.join();13. What is the ExecutorService framework?
Answer: The ExecutorService framework simplifies the management of threads by providing a higher-level replacement for the Thread class. It includes methods for managing thread execution and controlling the thread pool.
javaExecutorService executorService = Executors.newFixedThreadPool(10);
// Submitting tasks to the executor service
executorService.submit(() -> {
// Task code
});
// Shutting down the executor service
executorService.shutdown();14. Explain the concept of the Java Memory Model (JMM).
Answer: The Java Memory Model (JMM) is a specification that describes how Java threads interact through memory. It ensures visibility of changes made by one thread to other threads.
15. How can you use the isAlive() method?
Answer: The isAlive() method checks whether a thread is still running.
javaThread myThread = new Thread(() -> {
// Code
});
// Start the thread
myThread.start();
// Check if the thread is alive
boolean alive = myThread.isAlive();16. Explain the concept of thread safety.
Answer: Thread safety ensures that a piece of code or an object can be safely used by multiple threads without causing data corruption. Synchronization mechanisms like synchronized or volatile are used to achieve thread safety.
17. What is the purpose of the CountDownLatch class?
Answer: CountDownLatch is a synchronization aid that allows a thread to wait until a set of operations being performed in other threads completes.
javaCountDownLatch latch = new CountDownLatch(3);
// Thread 1
new Thread(() -> {
// Code
latch.countDown();
}).start();
// Thread 2
new Thread(() -> {
// Code
latch.countDown();
}).start();
// Main thread waits for both threads to finish
latch.await();18. What is the significance of the BlockingQueue interface?
Answer: The BlockingQueue interface in Java provides thread-safe implementation of producer-consumer design patterns. It helps in communication between producer and consumer threads.
javaBlockingQueue<String> queue = new LinkedBlockingQueue<>();
// Producer thread
new Thread(() -> {
// Produce item and put it in the queue
queue.put("item");
}).start();
// Consumer thread
new Thread(() -> {
// Consume item from the queue
String item = queue.take();
}).start();19. Explain the concept of the ThreadGroup class.
Answer: ThreadGroup is a class in Java that represents a group of threads. It provides a convenient way to manage and manipulate multiple threads as a single unit.
javaThreadGroup group = new ThreadGroup("MyThreadGroup");
// Creating threads in the thread group
Thread thread1 = new Thread(group, () -> {
// Code
});
Thread thread2 = new Thread(group, () -> {
// Code
});20. What is the ScheduledExecutorService interface used for?
Answer: ScheduledExecutorService is a subinterface of ExecutorService that supports the scheduling of tasks. It can be used to schedule tasks to run periodically or after a delay.
javaScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
// Schedule a task to run after a delay
scheduler.schedule(() -> {
// Task code
}, 5, TimeUnit.SECONDS);These questions cover various aspects of multithreading in Java and are designed to assess an experienced developer's understanding and practical knowledge of working with threads in Java.

Comments
Post a Comment