Multithreading and Concurrency

Multithreading allows multiple threads to run concurrently, improving the performance of applications. Understanding how to manage threads and handle synchronization is crucial for building efficient Java applications.

For more information on multithreading and concurrency, refer to our article: Multithreading and Concurrency.

Questions and Answers on Multithreading

1. What is a thread in Java?

A thread is a lightweight process that can run concurrently with other threads.

2. How do you create a thread in Java?

You can create a thread by extending the Thread class or implementing the Runnable interface.

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}
MyThread t = new MyThread();
t.start();

3. What is the difference between Runnable and Thread?

Runnable is an interface that can be implemented by any class, while Thread is a class that can be extended.

4. What is the start() method?

The start() method is used to begin the execution of a thread.

5. What is the run() method?

The run() method contains the code that is executed when the thread is started.

6. What is the sleep() method?

The sleep() method pauses the execution of the current thread for a specified time.

try {
    Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
    e.printStackTrace();
}

7. What is thread priority?

Thread priority is a value that determines the order in which threads are scheduled for execution.

8. How do you set thread priority?

You can set thread priority using the setPriority() method.

Thread t = new Thread();
t.setPriority(Thread.MAX_PRIORITY);

9. What is synchronization?

Synchronization is a mechanism that ensures that only one thread can access a resource at a time.

10. How do you synchronize a method?

You can synchronize a method by using the synchronized keyword.

public synchronized void synchronizedMethod() {
    // synchronized code
}

11. What is a synchronized block?

A synchronized block is a block of code that can only be accessed by one thread at a time.

public void method() {
    synchronized(this) {
        // synchronized code
    }
}

12. What is a deadlock?

A deadlock is a situation where two or more threads are blocked forever, waiting for each other.

13. How can you prevent deadlock?

You can prevent deadlock by ensuring that all threads acquire locks in a consistent order.

14. What is the join() method?

The join() method allows one thread to wait for the completion of another thread.

Thread t = new Thread();
t.start();
t.join(); // Wait for t to finish

15. What is the yield() method?

The yield() method is a hint to the thread scheduler that the current thread is willing to yield its current use of the CPU.

16. What is the interrupt() method?

The interrupt() method is used to interrupt a thread that is in a waiting or sleeping state.

17. What is the volatile keyword?

The volatile keyword indicates that a variable's value will be modified by different threads.

18. What is the ThreadLocal class?

The ThreadLocal class provides thread-local variables that are accessible only by the thread that created them.

19. What is the Executor framework?

The Executor framework provides a higher-level replacement for managing threads and thread pools.

20. How do you create a thread pool?

You can create a thread pool using the Executors.newFixedThreadPool() method.

ExecutorService executor = Executors.newFixedThreadPool(10);

21. What is a Callable?

A Callable is similar to a Runnable but can return a result and throw a checked exception.

22. How do you submit a task to an ExecutorService?

You can submit a task using the submit() method.

Future<String> future = executor.submit(new Callable<>() {
    public String call() {
        return "Task completed";
    }
});

23. What is a Future?

A Future represents the result of an asynchronous computation.

24. How do you retrieve the result from a Future?

You can retrieve the result using the get() method.

String result = future.get();

25. What is a CountDownLatch?

A CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

26. How do you use a CountDownLatch?

You can use a CountDownLatch by initializing it with a count and calling countDown() in the threads that complete their tasks.

CountDownLatch latch = new CountDownLatch(3);
// In worker threads
latch.countDown();

27. What is a CyclicBarrier?

A CyclicBarrier is a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.

28. How do you use a CyclicBarrier?

You can use a CyclicBarrier by initializing it with a number of parties and calling await() in each thread.

CyclicBarrier barrier = new CyclicBarrier(3);
// In worker threads
barrier.await();

29. What is a Semaphore?

A Semaphore is a counting semaphore that can be used to control access to a resource by multiple threads.

30. How do you use a Semaphore?

You can use a Semaphore by initializing it with a number of permits and calling acquire() and release().

Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
// critical section
semaphore.release();

31. What is the Fork/Join framework?

The Fork/Join framework is designed to take advantage of multiple processors by breaking tasks into smaller subtasks.

32. What is a RecursiveTask?

A RecursiveTask is a type of ForkJoinTask that returns a result.

33. What is a RecursiveAction?

A RecursiveAction is a type of ForkJoinTask that does not return a result.

34. How do you use the Fork/Join framework?

You can use the Fork/Join framework by creating a ForkJoinPool and invoking tasks.

ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new MyRecursiveTask());

35. What is the difference between wait() and sleep()?

wait() releases the lock and waits for a notification, while sleep() does not release the lock.

36. What is the notify() method?

The notify() method wakes up a single thread that is waiting on the object's monitor.

37. What is the notifyAll() method?

The notifyAll() method wakes up all threads that are waiting on the object's monitor.

38. What is the difference between a thread and a process?

A thread is a lightweight process that shares the same memory space, while a process has its own memory space.

39. What is thread safety?

Thread safety is a property of a program that guarantees safe execution by multiple threads without unintended interactions.

40. How do you achieve thread safety?

You can achieve thread safety by using synchronization, locks, or concurrent collections.

41. What is a ReentrantLock?

A ReentrantLock is a lock that allows a thread to enter a lock it already holds.

42. How do you use a ReentrantLock?

You can use a ReentrantLock by creating an instance and using lock() and unlock() methods.

ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}

43. What is a ReadWriteLock?

A ReadWriteLock allows multiple threads to read or one thread to write, providing better concurrency.

44. How do you use a ReadWriteLock?

You can use a ReadWriteLock by creating an instance and using readLock() and writeLock().

ReadWriteLock rwLock = new ReentrantReadWriteLock();
rwLock.readLock().lock();
try {
    // read operation
} finally {
    rwLock.readLock().unlock();
}

45. What is the Thread.sleep() method used for?

The Thread.sleep() method is used to pause the execution of the current thread for a specified duration.

46. What is the Thread.interrupt() method used for?

The Thread.interrupt() method is used to interrupt a thread that is in a waiting or sleeping state.

47. What is the Thread.isAlive() method?

The Thread.isAlive() method checks if a thread has been started and has not yet died.

48. What is the Thread.getName() method?

The Thread.getName() method returns the name of the thread.

49. What is the Thread.setName() method?

The Thread.setName() method sets the name of the thread.

50. What is the ThreadGroup class?

The ThreadGroup class is used to group multiple threads into a single group for easier management.

Go Back Home!!