Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MultithreadingInterview Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

1) What is multithreading?

Multithreading is a process of executing multiple threads simultaneously. Multithreading is used to


obtain the multitasking. It consumes less memory and gives the fast and efficient performance. Its
main advantages are:

o Threads share the same address space.


o The thread is lightweight.
o The cost of communication between the processes is low.

2) What is the thread?


A thread is a lightweight subprocess. It is a separate path of execution because each thread runs in
a different stack frame. A process may contain multiple threads. Threads share the process resources,
but still, they execute independently.

3) Differentiate between process and thread?


There are the following differences between the process and thread.

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?

o The process of communication between synchronized threads is termed as inter-thread


communication.
o Inter-thread communication is used to avoid thread polling in Java.
o The thread is paused running in its critical section, and another thread is allowed to enter (or
lock) in the same critical section to be executed.
o It can be obtained by wait(), notify(), and notifyAll() methods.

5) What is the purpose of wait() method in Java?


The wait() method is provided by the Object class in Java. This method is used for inter-thread
communication in Java. The java.lang.Object.wait() is used to pause the current thread, and wait until
another thread does not call the notify() or notifyAll() method. Its syntax is given below.

public final void wait()


6) Why must wait() method be called from the synchronized block?
We must call the wait method otherwise it will
throw java.lang.IllegalMonitorStateException exception. Moreover, we need wait() method for
inter-thread communication with notify() and notifyAll(). Therefore It must be present in the
synchronized block for the proper and correct communication.

7) What are the advantages of multithreading?


Multithreading programming has the following advantages:

o Multithreading allows an application/program to be always reactive for input, even already


running with some background tasks
o Multithreading allows the faster execution of tasks, as threads execute independently.
o Multithreading provides better utilization of cache memory as threads share the common
memory resources.
o Multithreading reduces the number of the required server as one server can execute multiple
threads at a time.

8) What are the states in the lifecycle of a Thread?


A thread can have one of the following states during its lifetime:

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.

10) What is context switching?


In Context switching the state of the process (or thread) is stored so that it can be restored and
execution can be resumed from the same point later. Context switching enables the multiple
processes to share the same CPU.

11) Differentiate between the Thread class and Runnable interface for
creating a Thread?
The Thread can be created by using two ways.

o By extending the Thread class


o By implementing the Runnable interface

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().

12) What does join() method?


The join() method waits for a thread to die. In other words, it causes the currently running threads
to stop executing until the thread it joins with completes its task. Join method is overloaded in
Thread class in the following ways.

o public void join()throws InterruptedException


o public void join(long milliseconds)throws InterruptedException

13) Describe the purpose and working of sleep() method.


The sleep() method in java is used to block a thread for a particular time, which means it pause the
execution of a thread for a specific time. There are two methods of doing so.

Syntax:

o public static void sleep(long milliseconds)throws InterruptedException


o public static void sleep(long milliseconds, int nanos)throws InterruptedException

Working of sleep() method

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.

14) What is the difference between wait() and sleep() method?

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.

15) Is it possible to start a thread twice?


No, we cannot restart the thread, as once a thread started and executed, it goes to the Dead state.
Therefore, if we try to start a thread twice, it will give a runtimeException
"java.lang.IllegalThreadStateException". Consider the following example.

1. public class Multithread1 extends Thread


2. {
3. public void run()
4. {
5. try {
6. System.out.println("thread is executing now........");
7. } catch(Exception e) {
8. }
9. }
10. public static void main (String[] args) {
11. Multithread1 m1= new Multithread1();
12. m1.start();
13. m1.start();
14. }
15. }

Output

thread is executing now........


Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at Multithread1.main(Multithread1.java:13)

16) Can we call the run() method instead of start()?


Yes, calling run() method directly is valid, but it will not work as a thread instead it will work as a
normal object. There will not be context-switching between the threads. When we call the start()
method, it internally calls the run() method, which creates a new stack for a thread while directly
calling the run() will not create a new stack.

17) What about the daemon threads?


The daemon threads are the low priority threads that provide the background support and services
to the user threads. Daemon thread gets automatically terminated by the JVM if the program
remains with the daemon thread only, and all other user threads are ended/died. There are two
methods for daemon thread available in the Thread class:

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.

1. class Testdaemon1 extends Thread{


2. public void run(){
3. System.out.println("Running thread is daemon...");
4. }
5. public static void main (String[] args) {
6. Testdaemon1 td= new Testdaemon1();
7. td.start();
8. setDaemon(true);// It will throw the exception: td.
9. }
10. }

Output

Running thread is daemon...


Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1359)
at Testdaemon1.main(Testdaemon1.java:8)

19)What is shutdown hook?


The shutdown hook is a thread that is invoked implicitly before JVM shuts down. So we can use it to
perform clean up the resource or save the state when JVM shuts down normally or abruptly. We can
add shutdown hook by using the following method:

1. public void addShutdownHook(Thread hook){}


2. Runtime r=Runtime.getRuntime();
3. r.addShutdownHook(new MyThread());

Some important points about shutdown hooks are :


o Shutdown hooks initialized but can only be started when JVM shutdown occurred.
o Shutdown hooks are more reliable than the finalizer() because there are very fewer chances
that shutdown hooks not run.
o The shutdown hook can be stopped by calling the halt(int) method of Runtime class.

20)When should we interrupt a thread?


We should interrupt a thread when we want to break out the sleep or wait state of a thread. We can
interrupt a thread by calling the interrupt() throwing the InterruptedException.

21) What is the synchronization?


Synchronization is the capability to control the access of multiple threads to any shared resource. It
is used:

1. To prevent thread interference.


2. To prevent consistency problem.

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:

o by the synchronized method


o by synchronized block
o by static synchronization

Syntax for synchronized block

1. synchronized(object reference expression)


2. {
3. //code block
4. }
5.

22) What is the purpose of the Synchronized block?


The Synchronized block can be used to perform synchronization on any specific resource of the
method. Only one thread at a time can execute on a particular resource, and all other threads which
attempt to enter the synchronized block are blocked.
o Synchronized block is used to lock an object for any shared resource.
o The scope of the synchronized block is limited to the block on which, it is applied. Its scope
is smaller than a method.

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.

24) What is static synchronization?


If you make any static method as synchronized, the lock will be on the class not on the object. If we
use the synchronized keyword before a method so it will lock the object (one thread can access an
object at a time) but if we use static synchronized so it will lock a class (one thread can access a class
at a time).

25)What is the difference between notify() and notifyAll()?


The notify() is used to unblock one waiting thread whereas notifyAll() method is used to unblock all
the threads in waiting state.

26)What is the deadlock?


Deadlock is a situation in which every thread is waiting for a resource which is held by some other
waiting thread. In this situation, Neither of the thread executes nor it gets the chance to be executed.
Instead, there exists a universal waiting state among all the threads. Deadlock is a very complicated
situation which can break our code at runtime.

27) How to detect a deadlock condition? How can it be avoided?


We can detect the deadlock condition by running the code on cmd and collecting the Thread Dump,
and if any deadlock is present in the code, then a message will appear on cmd.

Ways to avoid the deadlock condition in Java:

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.

28) What is Thread Scheduler in java?


In Java, when we create the threads, they are supervised with the help of a Thread Scheduler, which
is the part of JVM. Thread scheduler is only responsible for deciding which thread should be
executed. Thread scheduler uses two mechanisms for scheduling the threads: Preemptive and Time
Slicing.

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

29) Does each thread have its stack in multithreaded programming?


Yes, in multithreaded programming every thread maintains its own or separate stack area in memory
due to which every thread is independent of each other.

30) How is the safety of a thread achieved?


If a method or class object can be used by multiple threads at a time without any race condition,
then the class is thread-safe. Thread safety is used to make a program safe to use in multithreaded
programming. It can be achieved by the following ways:

o Synchronization
o Using Volatile keyword
o Using a lock based mechanism
o Use of atomic wrapper classes

31) What is race-condition?


A Race condition is a problem which occurs in the multithreaded programming when various threads
execute simultaneously accessing a shared resource at the same time. The proper use of
synchronization can avoid the Race condition.
32) What is the volatile keyword in java?
Volatile keyword is used in multithreaded programming to achieve the thread safety, as a change in
one volatile variable is visible to all other threads so one variable can be used by one thread at a
time.

33) What do you understand by thread pool?

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.

The advantages of the thread pool are :

o Using a thread pool, performance can be enhanced.


o Using a thread pool, better system stability can occur.

34) What are the main components of concurrency API?


Concurrency API can be developed using the class and interfaces of java.util.Concurrent package.
There are the following classes and interfaces in java.util.Concurrent package.

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

35) What is the Executor interface in Concurrency API in Java?


The Executor Interface provided by the package java.util.concurrent is the simple interface used to
execute the new task. The execute() method of Executor interface is used to execute some given
command. The syntax of the execute() method is given below.

void execute(Runnable command)

Consider the following example:

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

36) What is BlockingQueue?


The java.util.concurrent.BlockingQueue is the subinterface of Queue that supports the operations
such as waiting for the space availability before inserting a new value or waiting for the queue to
become non-empty before retrieving an element from it. Consider the following example.

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

37) How to implement producer-consumer problem by using


BlockingQueue?
The producer-consumer problem can be solved by using BlockingQueue in the following way.

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.

39) What is the Atomic action in Concurrency in Java?

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.

40) What is lock interface in Concurrency API in Java?


The java.util.concurrent.locks.Lock interface is used as the synchronization mechanism. It works
similar to the synchronized block. There are a few differences between the lock and synchronized
block that are given below.
o Lock interface provides the guarantee of sequence in which the waiting thread will be given
the access, whereas the synchronized block doesn't guarantee it.
o Lock interface provides the option of timeout if the lock is not granted whereas the
synchronized block doesn't provide that.
o The methods of Lock interface, i.e., Lock() and Unlock() can be called in different methods
whereas single synchronized block must be fully contained in a single method.

41) Explain the ExecutorService Interface.


The ExecutorService Interface is the subinterface of Executor interface and adds the features to
manage the lifecycle. Consider the following example.

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

42) What is the difference between Synchronous programming and


Asynchronous programming regarding a thread?
Synchronous programming: In Synchronous programming model, a thread is assigned to
complete a task and hence thread started working on it, and it is only available for other tasks once
it will end the assigned task.

Asynchronous Programming: In Asynchronous programming, one job can be completed by


multiple threads and hence it provides maximum usability of the various threads.

43) What do you understand by Callable and Future in Java?


Java Callable interface: In Java5 callable interface was provided by the package java.util.concurrent.
It is similar to the Runnable interface but it can return a result, and it can throw an Exception. It also
provides a run() method for execution of a thread. Java Callable can return any object as it uses
Generic.

Syntax:

public interface Callable<V>

Java Future interface: Java Future interface gives the result of a concurrent process. The Callable
interface returns the object of java.util.concurrent.Future.

Java Future provides following methods for implementation.


o cancel(boolean mayInterruptIfRunning): It is used to cancel the execution of the assigned
task.
o get(): It waits for the time if execution not completed and then retrieved the result.
o isCancelled(): It returns the Boolean value as it returns true if the task was canceled before
the completion.
o isDone(): It returns true if the job is completed successfully else returns false.

44. What is the difference between ScheduledExecutorService and


ExecutorService interface?
ExecutorServcie and ScheduledExecutorService both are the interfaces of java.util.Concurrent
package but scheduledExecutorService provides some additional methods to execute the Runnable
and Callable tasks with the delay or every fixed time period.

45) Define FutureTask class in Java?


Java FutureTask class provides a base implementation of the Future interface. The result can only be
obtained if the execution of one task is completed, and if the computation is not achieved then get
method will be blocked. If the execution is completed, then it cannot be re-started and can't be
canceled.

Syntax

public class FutureTask<V> extends Object implements RunnableFuture<V>

Q-1 What is multitasking?


A multitasking operating system is an operating system that gives you the perception
of 2 or more tasks/jobs/processes running at the same time. It does this by dividing
system resources amongst these tasks/jobs/processes and switching between the
tasks/jobs/processes while they are executing over and over again. Usually, the CPU
processes only one task at a time but the switching is so fast that it looks like the CPU
is executing multiple processes at a time. They can support either preemptive
multitasking, where the OS provides time to applications (virtually all modern OS), or
cooperative multitasking, where the OS waits for the program to give back control
(Windows 3.x, Mac OS 9, and earlier), leading to hangs and crashes. Also known as
Timesharing, multitasking is a logical extension of multiprogramming.
Multitasking programming is of two types which are as follows:
1. Process-based Multitasking
2. Thread-based Multitasking
Note: Performing multiple tasks at one time is referred to as multithreading in java
which is of two types namely Process-based multithreading and Thread based
multithreading.
Q-2 How can you identify the process?
Any program which is in a working state is referred to as a process. These processes
do have threads that are single dispatchable units.
Q-3 How do you see a thread?
In order to see threads status let us take windows as an operating system, it
illustrates then we’d have ProcessExplorer where you can see GUI shown below for
windows operating systems.
This PC > OS > Users > GeeksforGeeks > Downloads > ProcessExplorer
ProcessExplorer is illustrated below in the windows operating systems
Note: All of them as listed in the above media are the processes as shown above
where at a time many are running in parallel to each other henceforth illustrating
multiprocessing in the Jwindows operating system.
As we have seen threads do reside in a single process so we have to deep dive into a
specific process to see them in order to show users how multithreading is going on in
the computers at the backend. For example: let us pick a random process from the
above media consisting of various processes say it be ‘chrome’. Now we need to
right-click over the process and click the properties’ menu.
From the above media, it is clearly perceived that chrome is a process and after
proceeding with the steps to figure out threads running inside the chrome process
we go to properties of the process ‘chrome’ below pictorial output will be generated
representing threads running in the process chrome.
Note: If we look scroll way from up to down then it will be seeing some colors
against a few of those threads. Here green color threads are associated as the newly
created threads and red colors associated threads are representing the closed
threads.

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:

Thread-based multitasking refers to executing several tasks simultaneously where


each task is a separate independent part of the same program known as a thread.
For example, JUnits uses threads to run test cases in parallel. Henceforth, process-
based multitasking is a bigger scenario handling process where threads handle the
details. It is already discussed to deeper depth already with visual aids.
Q-5 Which Kind of Multitasking is Better and Why?
Thread-based multitasking is better as multitasking of threads requires less
overhead as compared to process multitasking because processes are heavyweight
in turn requiring their own separate address space in memory while threads being
very light-weight processes and share the same address space as cooperatively
shared by heavyweight processes.
Switching is a secondary reason as inter-process communication is expensive and
limited. Context switching from one process to another is cost hefty whereas inter-
thread communication is inexpensive and context switching from one thread to
another is lower in cost.
Note: However java programs make use of process-based multitasking
environments, but this feature is not directly under Java’s direct control while
multithreading is complete.
Q-6 What is a thread?
Threads are lightweight processes within processes as seen. In java, there are two
ways of creating threads namely via Thread class and via Runnable interface.
Q-7 What are the different states of a thread, or what is thread lifecycle?
A thread in Java at any point of time exists in any one of the following states. A
thread lies only in one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
Q-8 What is the task of the main thread?
All Java programs have at least one thread, known as the main thread which is
created by JVM at the program start when the main() method is invoked with the
main thread as depicted from the output perceived from pseudo-code illustration.
Illustration:
System.out.println(“Mayank Solanki”);
Output: Mayank Solanki
System.out.println(Thread.currentthread().getname());
Output: main
Q-9 What are the Different Types of threads in Java?
There are two types of threads in Java as follows:
• User thread
• Daemon thread
User threads are created by java developers for example Main thread. All threads are
created inside the main() method are by default non-daemon thread because the
‘main’ thread is non-daemon. Daemon thread is a low-priority thread that runs in the
background to perform tasks such as garbage collection, etc. They do not prevent
daemon threads from exiting when all user threads finish their execution. JVM
terminates itself when all non-daemon threads finish their execution. JVM does not
care whether a thread is running or not, if JVM finds a running daemon thread it
terminates the thread and after that shutdown itself.
Q-10 How to Create a User thread?
As discussed earlier when the JVM starts it creates a main thread over which
the program is run unless an additional thread is not created by the user. The first
thing “Main” thread looks for ‘public static void main(String [] args)’ method to invoke
it as it acts as an entry point to the program. All other threads created in main acts as
child threads of the “Main” thread.
User thread can be implemented in two ways listed below:
1. Using Thread class by extending java.lang.Thread class.
2. Using Runnable Interface by implementing it.
Q-11 How to set the name of the thread?
We can name a thread by using a method been already up there known
as setName() replacing default naming which was ‘Thread-0’, ‘Thread-1’, and so on.
thread_class_object.setName("Name_thread_here");
Q-12 What is thread priority?
Priorities in threads is a concept where each thread is having a priority which in
layman’s language one can say every object is having priority here which is
represented by numbers ranging from 1 to 10.
• The default priority is set to 5 as excepted.
• Minimum priority is set to 1.
• Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:
1. public static int NORM_PRIORITY
2. public static int MIN_PRIORITY
3. public static int MAX_PRIORITY
Q-13 How deadlock plays a important role in multithreading?
If we do incorporate threads in operating systems one can perceive that the process
scheduling algorithms in operating systems are strongly deep-down working on the
same concept incorporating thread in Gantt charts. A few of the most popular are
listed below which wraps up all of them and are used practically in software
development.

• First In First Out


• Last In First Out
• Round Robin Scheduling
Now one Imagine the concept of Deadlock in operating systems with threads by now
how the switching is getting computed over internally if one only has an overview of
them.

Q-14 Why output is not ordered?


Scheduling of threads involves two boundary scheduling,
• Scheduling of user-level threads (ULT) to kernel-level threads (KLT) via
lightweight process (LWP) by the application developer.
• Scheduling of kernel-level threads by the system scheduler to perform
different unique os functions.

If multiple threads are waiting to execute then thread execution is decided by


“ThreadScheduler” which is a part of JVM hence its vendor dependent resulting in
unexpected execution of output order.
Note:
• In multithreading, the guarantee of order is very less where we can predict
possible outputs but not exactly one.
• Also, note that synchronization when incorporated with multithreading does
affect our desired output simply by using the keyword ‘synchronized’.
It is as illustrated in the below illustration which is as follows:
Q-15 What is Daemon Thread in Java and explain their properties?
Daemon thread is a low-priority thread that runs in the background to perform tasks
such as garbage collection. It does possess certain specific properties as listed
below:
• They can not prevent the JVM from exiting when all the user threads finish
their execution.
• JVM terminates itself when all user threads finish their execution
• If JVM finds a running daemon thread, it terminates the thread and after that
shutdown itself. JVM does not care whether the Daemon thread is running
or not.
• It is an utmost low priority thread
Note: The main difference between user thread and daemon thread is that JVM does
not wait for daemon thread before exiting while it do waits for the user thread.
Q-16 How to Make User Thread to Daemon Thread?
It is carried out with the help of two methods listed in ‘Thread class’ known
as setDaemon() and isDaemon(). First, the setDaemon() method converts user
thread to daemon thread and vice-versa. This method can only be called before
starting the thread using start() method else is called after starting the thread with
will throw IllegalThreadStateException After this, isDaemon() method is used
which returns a boolean true if the thread is daemon else returns false if it is a non-
daemon thread.
Q-17 What are the tasks of the start() method?
The primary task of the start() method is to register the thread with the thread
scheduler, so one can tell what child thread should perform, when, and how it will
be scheduled that is handled by the thread scheduler. The secondary task is to call
the corresponding run() method got the threads.
Q-18 What is the difference between the start() and run() method?
First, both methods are operated in general over the thread. So if we do use
threadT1.start() then this method will look for the run() method to create a new
thread. While in case of theadT1.run() method will be executed just likely the normal
method by the “Main” thread without the creation of any new thread.
Note: If we do replace start() method with run() method then the entire program is
carried by ‘main’ thread.
Q-19 Can we Overload run() method? What if we do not override the run()
method?

Yes, it is possible to overload run() by passing parameters to it and also keeping a


check over to comment down @override from the run() method.
It should be as good as a thread wherein thread we do not have any arguments, so
practice to overload is to comment on the call out for overloaded run() method. Now,
so we need to acknowledge the same whether the output is the same or not if we
have not overloaded it.
If we have overloaded the run() method, then we will observe that output is always
the main method as can be perceived from the stack call from the above image. It is
because if we debug the code as provided in the link below we see as soon as the
start() method is called again, run() is called because we have not overridden the
run() method.
Q-20 Can we Override the start() method?
Even if we override the start() method in the custom class then no initializations will
be carried on by the Thread class for us. The run() method is also not called and even
a new thread is also not created.
Note: We can not restart the same thread again as we will
get IllegalThreadStateException from java.lang package. Alongside we can not do
this indirectly with usage of ‘super.start()’ method.

You might also like