MultithreadingInterview Questions
MultithreadingInterview Questions
MultithreadingInterview Questions
o A Program in the execution is called the process whereas; A thread is a subset of the process
o Processes are independent whereas threads are the subset of process.
o Process have different address space in memory, while threads contain a shared address
space.
o Context switching is faster between the threads as compared to processes.
o Inter-process communication is slower and expensive than inter-thread communication.
o Any change in Parent process doesn't affect the child process whereas changes in parent
thread can affect the child thread.
4) What do you understand by inter-thread communication?
1. New: In this state, a Thread class object is created using a new operator, but the thread is not
alive. Thread doesn't start until we call the start() method.
2. Runnable: In this state, the thread is ready to run after calling the start() method. However,
the thread is not yet selected by the thread scheduler.
3. Running: In this state, the thread scheduler picks the thread from the ready state, and the
thread is running.
4. Waiting/Blocked: In this state, a thread is not running but still alive, or it is waiting for the
other thread to finish.
5. Dead/Terminated: A thread is in terminated or dead state when the run() method exits.
9) What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
11) Differentiate between the Thread class and Runnable interface for
creating a Thread?
The Thread can be created by using two ways.
However, the primary differences between both the ways are given below:
o By extending the Thread class, we cannot extend any other class, as Java does not allow
multiple inheritances while implementing the Runnable interface; we can also extend other
base class(if required).
o By extending the Thread class, each of thread creates the unique object and associates with
it while implementing the Runnable interface; multiple threads share the same object
o Thread class provides various inbuilt methods such as getPriority(), isAlive and many more
while the Runnable interface provides a single method, i.e., run().
Syntax:
When we call the sleep() method, it pauses the execution of the current thread for the given time
and gives priority to another thread(if available). Moreover, when the waiting time completed then
again previous thread changes its state from waiting to runnable and comes in running state, and
the whole process works so on till the execution doesn't complete.
wait() sleep()
1) The wait() method is defined in Object The sleep() method is defined in Thread
class. class.
2) The wait() method releases the lock. The sleep() method doesn't release the
lock.
Output
o public void setDaemon(boolean status): It used to mark the thread daemon thread or a
user thread.
o public boolean isDaemon(): It checks the thread is daemon or not.
18)Can we make the user thread as daemon thread if the thread is started?
No, if you do so, it will throw IllegalThreadStateException. Therefore, we can only create a daemon
thread before starting the thread.
Output
When the multiple threads try to do the same task, there is a possibility of an erroneous result, hence
to remove this issue, Java uses the process of synchronization which allows only one thread to be
executed at a time. Synchronization can be achieved in three ways:
23)Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible
to any thread other than the one that explicitly claimed it.
o Avoid Nested lock: Nested lock is the common reason for deadlock as deadlock occurs when
we provide locks to various threads so we should give one lock to only one thread at some
particular time.
o Avoid unnecessary locks: we must avoid the locks which are not required.
o Using thread join: Thread join helps to wait for a thread until another thread doesn't finish
its execution so we can avoid deadlock by maximum use of join method.
Java thread scheduler also works for deciding the following for a thread:
o It selects the priority of the thread.
o It determines the waiting time for a thread
o It checks the Nature of thread
o Synchronization
o Using Volatile keyword
o Using a lock based mechanism
o Use of atomic wrapper classes
o Java Thread pool represents a group of worker threads, which are waiting for the task to be
allocated.
o Threads in the thread pool are supervised by the service provider which pulls one thread from
the pool and assign a job to it.
o After completion of the given task, thread again came to the thread pool.
o The size of the thread pool depends on the total number of threads kept at reserve for
execution.
o Executor
o FarkJoinPool
o ExecutorService
o ScheduledExecutorService
o Future
o TimeUnit(Enum)
o CountDownLatch
o CyclicBarrier
o Semaphore
o ThreadFactory
o BlockingQueue
o DelayQueue
o Locks
o Phaser
1. import java.util.concurrent.Executor;
2. import java.util.concurrent.Executors;
3. import java.util.concurrent.ThreadPoolExecutor;
4. import java.util.concurrent.TimeUnit;
5.
6. public class TestThread {
7. public static void main(final String[] arguments) throws InterruptedException {
8. Executor e = Executors.newCachedThreadPool();
9. e.execute(new Thread());
10. ThreadPoolExecutor pool = (ThreadPoolExecutor)e;
11. pool.shutdown();
12. }
13.
14. static class Thread implements Runnable {
15. public void run() {
16. try {
17. Long duration = (long) (Math.random() * 5);
18. System.out.println("Running Thread!");
19. TimeUnit.SECONDS.sleep(duration);
20. System.out.println("Thread Completed");
21. } catch (InterruptedException ex) {
22. ex.printStackTrace();
23. }
24. }
25. }
26. }
Output
Running Thread!
Thread Completed
1. import java.util.Random;
2. import java.util.concurrent.ArrayBlockingQueue;
3. import java.util.concurrent.BlockingQueue;
4.
5. public class TestThread {
6.
7. public static void main(final String[] arguments) throws InterruptedException {
8. BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
9.
10. Insert i = new Insert(queue);
11. Retrieve r = new Retrieve(queue);
12.
13. new Thread(i).start();
14. new Thread(r).start();
15.
16. Thread.sleep(2000);
17. }
18.
19.
20. static class Insert implements Runnable {
21. private BlockingQueue<Integer> queue;
22.
23. public Insert(BlockingQueue queue) {
24. this.queue = queue;
25. }
26.
27. @Override
28. public void run() {
29. Random random = new Random();
30.
31. try {
32. int result = random.nextInt(200);
33. Thread.sleep(1000);
34. queue.put(result);
35. System.out.println("Added: " + result);
36.
37. result = random.nextInt(10);
38. Thread.sleep(1000);
39. queue.put(result);
40. System.out.println("Added: " + result);
41.
42. result = random.nextInt(50);
43. Thread.sleep(1000);
44. queue.put(result);
45. System.out.println("Added: " + result);
46. } catch (InterruptedException e) {
47. e.printStackTrace();
48. }
49. }
50. }
51.
52. static class Retrieve implements Runnable {
53. private BlockingQueue<Integer> queue;
54.
55. public Retrieve(BlockingQueue queue) {
56. this.queue = queue;
57. }
58.
59. @Override
60. public void run() {
61.
62. try {
63. System.out.println("Removed: " + queue.take());
64. System.out.println("Removed: " + queue.take());
65. System.out.println("Removed: " + queue.take());
66. } catch (InterruptedException e) {
67. e.printStackTrace();
68. }
69. }
70. }
71. }
Output
Added: 96
Removed: 96
Added: 8
Removed: 8
Added: 5
Removed: 5
1. import java.util.concurrent.BlockingQueue;
2. import java.util.concurrent.LinkedBlockingQueue;
3. import java.util.logging.Level;
4. import java.util.logging.Logger;
5. public class ProducerConsumerProblem {
6. public static void main(String args[]){
7. //Creating shared object
8. BlockingQueue sharedQueue = new LinkedBlockingQueue();
9.
10. //Creating Producer and Consumer Thread
11. Thread prod = new Thread(new Producer(sharedQueue));
12. Thread cons = new Thread(new Consumer(sharedQueue));
13.
14. //Starting producer and Consumer thread
15. prod.start();
16. cons.start();
17. }
18.
19. }
20.
21. //Producer Class in java
22. class Producer implements Runnable {
23.
24. private final BlockingQueue sharedQueue;
25.
26. public Producer(BlockingQueue sharedQueue) {
27. this.sharedQueue = sharedQueue;
28. }
29.
30. @Override
31. public void run() {
32. for(int i=0; i<10; i++){
33. try {
34. System.out.println("Produced: " + i);
35. sharedQueue.put(i);
36. } catch (InterruptedException ex) {
37. Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
38. }
39. }
40. }
41.
42. }
43.
44. //Consumer Class in Java
45. class Consumer implements Runnable{
46.
47. private final BlockingQueue sharedQueue;
48.
49. public Consumer (BlockingQueue sharedQueue) {
50. this.sharedQueue = sharedQueue;
51. }
52.
53. @Override
54. public void run() {
55. while(true){
56. try {
57. System.out.println("Consumed: "+ sharedQueue.take());
58. } catch (InterruptedException ex) {
59. Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
60. }
61. }
62. }
63. }
Output
Produced: 0
Produced: 1
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Produced: 6
Produced: 7
Produced: 8
Produced: 9
Consumed: 0
Consumed: 1
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
Consumed: 7
Consumed: 8
Consumed: 9
38) What is the difference between Java Callable interface and Runnable
interface?
The Callable interface and Runnable interface both are used by the classes which wanted to execute
with multiple threads. However, there are two main differences between the both :
o A Callable <V> interface can return a result, whereas the Runnable interface cannot return
any result.
o A Callable <V> interface can throw a checked exception, whereas the Runnable interface
cannot throw checked exception.
o A Callable <V> interface cannot be used before the Java 5 whereas the Runnable interface
can be used.
o The Atomic action is the operation which can be performed in a single unit of a task without
any interference of the other operations.
o The Atomic action cannot be stopped in between the task. Once started it fill stop after the
completion of the task only.
o An increment operation such as a++ does not allow an atomic action.
o All reads and writes operation for the primitive variable (except long and double) are the
atomic operation.
o All reads and writes operation for the volatile variable (including long and double) are the
atomic operation.
o The Atomic methods are available in java.util.Concurrent package.
1. import java.util.concurrent.ExecutorService;
2. import java.util.concurrent.Executors;
3. import java.util.concurrent.TimeUnit;
4.
5. public class TestThread {
6. public static void main(final String[] arguments) throws InterruptedException {
7. ExecutorService e = Executors.newSingleThreadExecutor();
8.
9. try {
10. e.submit(new Thread());
11. System.out.println("Shutdown executor");
12. e.shutdown();
13. e.awaitTermination(5, TimeUnit.SECONDS);
14. } catch (InterruptedException ex) {
15. System.err.println("tasks interrupted");
16. } finally {
17.
18. if (!e.isTerminated()) {
19. System.err.println("cancel non-finished tasks");
20. }
21. e.shutdownNow();
22. System.out.println("shutdown finished");
23. }
24. }
25.
26. static class Task implements Runnable {
27.
28. public void run() {
29.
30. try {
31. Long duration = (long) (Math.random() * 20);
32. System.out.println("Running Task!");
33. TimeUnit.SECONDS.sleep(duration);
34. } catch (InterruptedException ex) {
35. ex.printStackTrace();
36. }
37. }
38. }
39. }
Output
Shutdown executor
shutdown finished
Syntax:
Java Future interface: Java Future interface gives the result of a concurrent process. The Callable
interface returns the object of java.util.concurrent.Future.
Syntax
Note: So for chrome to increase the performance by reducing the response time that
is referred to as Thread based multitasking.
Q-4 What is Multithreading and How it is Different from Multitasking?
Multithreading is a specialized form of multitasking. Process-based
multitasking refers to executing several tasks simultaneously where each task is a
separate independent process is Process-based multitasking.
Example: Running Java IDE and running TextEdit at the same time. Process-based
multitasking is represented by the below pictorial which is as follows: