Q #38) What is a Thread?
Ans: In Java, the flow of a execution is called Thread. Every java program has at least one thread called main thread, the Main thread is created by JVM. The user can define their own threads by extending Thread class (or) by implementing Runnable interface. Threads are executed concurrently.
Example:
1 | public static void main(String[] args){ //main thread starts here |
2 | } |
Q #39) How do you make a thread in Java?
Ans: There are two ways available in order to make a thread.
#1) Extend Thread class:
Extending a Thread class and override the run method. The thread is available in java.lang.thread.
Example:
1 | Public class Addition extends Thread { |
2 | public void run () { |
3 | } |
4 | } |
The disadvantage of using a thread class is that we cannot extend any other classes because we have already extend the thread class. We can overload the run () method in our class.
#2) Implement Runnable interface:
Another way is implementing the runnable interface. For that we should provide the implementation for run () method which is defined in the interface.
Example:
1 | Public class Addition implements Runnable { |
2 | public void run () { |
3 | } |
4 | } |
Q #40) Explain about join () method.
Ans: Join () method is used to join one thread with the end of the currently running thread.
Example:
1 | public static void main (String[] args){ |
2 | Thread t = new Thread (); |
3 | t.start (); |
4 | t.join (); |
5 | } |
From the above code, the main thread started the execution. When it reaches the code t.start() then ‘thread t’ starts the own stack for the execution. JVM switches between the main thread and ‘thread t’.
Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task, then only main thread started the execution.
It is a non-static method. Join () method has overloaded version. So we can mention the time duration in join () method also “.s”.
Q #41) What does yield method of the Thread class do?
Ans: A yield () method moves the currently running thread to a runnable state and allows the other threads for execution. So that equal priority threads have a chance to run. It is a static method. It doesn’t release any lock.
Yield () method moves the thread back to the Runnable state only, and not the thread to sleep (), wait () (or) block.
Example:
1 | public static void main (String[] args){ |
2 | Thread t = new Thread (); |
3 | t.start (); |
4 | } |
5 | public void run(){ |
6 | Thread.yield(); |
7 | } |
8 | } |
Q #42) Explain about wait () method.
Ans: wait () method is used to make the thread to wait in the waiting pool. When a wait () method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool. Wait () method tells the thread to wait for a given amount of time.
Then the thread will wake up after notify () (or) notify all () method is called.
Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in synchronization.
Example:
1 | public static void main (String[] args){ |
2 | Thread t = new Thread (); |
3 | t.start (); |
4 | Synchronized (t) { |
5 | Wait(); |
6 | } |
7 | } |
Q #43) Difference between notify() method and notifyAll() method in Java.
Ans: Given below are few differences between notify() method and notifyAll() method
notify() | notifyAll() |
---|---|
This method is used to send a signal to wake up a single thread in the waiting pool. | This method sends the signal to wake up all the threads in a waiting spool. |
Q #44) How to stop a thread in java? Explain about sleep () method in a thread?
Ans: We can stop a thread by using the following thread methods.
- Sleeping
- Waiting
- Blocked
Sleep:
Sleep () method is used to sleep the currently executing thread for the given amount of time. Once the thread is wake up it can move to the runnable state. So sleep () method is used to delay the execution for some period.
It is a static method.
Example:
Thread. Sleep (2000)
So it delays the thread to sleep 2 milliseconds. Sleep () method throws an uninterrupted exception, hence we need to surround the block with try/catch.
1 | public class ExampleThread implements Runnable{ |
2 | public static void main (String[] args){ |
3 | Thread t = new Thread (); |
4 | t.start (); |
5 | } |
6 | public void run(){ |
7 | try { |
8 | Thread.sleep( 2000 ); |
9 | } catch (InterruptedException e){ |
10 | } |
11 | } |
Q #45) When to use Runnable interface Vs Thread class in Java?
Ans: If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class.
If we are not going to extend any class then we can extend the thread class.
Q #46) Difference between start() and run() method of thread class.
Ans: Start() method creates new thread and the code inside the run () method is executed in the new thread. If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.
Q #47) What is Multi-threading?
Ans: Multiple threads are executed simultaneously. Each thread starts their own stack based on the flow (or) priority of the threads.
Example Program:
1 | public class MultipleThreads implements Runnable |
2 | { |
3 | public static void main (String[] args){ //Main thread starts here |
4 | Runnable r = new runnable (); |
5 | Thread t= new thread (); |
6 | t.start (); //User thread starts here |
7 | Addition add= new addition (); |
8 | } |
9 | public void run(){ |
10 | go(); |
11 | } //User thread ends here |
12 | } |
On the 1st line execution, JVM calls the main method and the main thread stack looks as shown below.
Once the execution reaches, t.start () line then a new thread is created and the new stack for the thread is also created. Now JVM switches to the new thread and the main thread are back to the runnable state.
The two stacks look as shown below.
Now, the user thread executed the code inside the run() method.
Once the run() method has completed, then JVM switches back to the main thread and the User thread has completed the task and the stack was disappeared.
JVM switches between each thread until both the threads are completed. This is called Multi-threading.
Q #48) Explain thread life cycle in Java.
Ans: Thread has the following states:
- New
- Runnable
- Running
- Non-runnable (Blocked)
- Terminated
- New:
In New state, Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.
- Runnable:
The Thread is in runnable state after invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state the thread is considered alive.
- Running:
The thread is in running state after it calls the run () method. Now the thread begins the execution.
- Non-Runnable(Blocked):
The thread is alive but it is not eligible to run. It is not in runnable state but also, it will return to runnable state after some time.
Example: wait, sleep, block.
- Terminated :
Once the run method is completed then it is terminated. Now the thread is not alive.
Q #49) What is Synchronization?
Ans: Synchronization makes only one thread to access a block of code at a time. If multiple thread accesses the block of code, then there is a chance for inaccurate results at the end. To avoid this issue, we can provide synchronization for the sensitive block of codes.
The synchronized keyword means that a thread needs a key in order to access the synchronized code.
Locks are per objects. Every Java object has a lock. A lock has only one key. A thread can access a synchronized method only if the thread can get the key to the objects lock.
For this, we use “Synchronized” keyword.
Example:
public class ExampleThread implements Runnable{ public static void main (String[] args){ Thread t = new Thread (); t.start (); } public void run(){ synchronized(object){ { } }
Q #50) What is the disadvantage of Synchronization?
Ans: Synchronization is not recommended to implement all the methods. Because if one thread accesses the synchronized code then the next thread should have to wait. So it makes slow performance on the other end.
Q #51) What is meant by Serialization?
Ans: Converting a file into a byte stream is known as Serialization. The objects in the file is converted to the bytes for security purposes. For this, we need to implement java.io.Serializable interface. It has no method to define.
Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword.
Q #52) What is the purpose of a transient variable?
Ans: Transient variables are not part of the serialization process. During deserialization, the transient variables values are set to default value. It is not used with static variables.
Example:
transient int numbers;
Q #53) Which methods are used during Serialization and Deserialization process?
Ans: ObjectOutputStream and ObjectInputStream classes are higher level java.io. package. We will use them with lower level classes FileOutputStream and FileInputStream.
ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a file.
ObjectInputStream.readObject —> Reads the file and deserializes the object.
To be serialized, an object must implement the serializable interface. If superclass implements Serializable, then the subclass will automatically be serializable.
Q #54) What is the purpose of a Volatile Variable?
Ans: Volatile variable values are always read from the main memory and not from thread’s cache memory. This is used mainly during synchronization. It is applicable only for variables.
Example:
volatile int number;
Q) What is the use of synchronized keyword?
Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method other threads have to wait until current thread finishes the execution and release lock. Synchronized keyword provides a lock on the object and thus prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){
//synchronized keyword on block of code
}
}
Why wait and notify is declared in Object class instead of Thread?
Wait, notify, notifyAll methods are only required when you want your threads to access a shared resource and a shared resource could be any java object which is on the heap. So, these methods are defined on the core Object class so that each object has control of allowing threads to wait on it’s monitor. Java doesn’t have any special object which is used for sharing a common resource. No such data structure is defined.So, onus is given on the Object class to be able to become shared resource providing it will helper methods like
wait()
,notify()
and notifyAll()
.
Java is based on Hoare‘s monitors idea. In Java all object has a monitor. Threads waits on monitors so, to perform a wait, we need 2 parameters:
– a Thread
– a monitor (any object)
– a monitor (any object)
In the Java design, the thread can not be specified, it is always the current thread running the code. However, we can specify the monitor (which is the object we call wait on). This is a good design, because if we could make any other thread to wait on a desired monitor, this would lead to an “intrusion”, posing difficulties on designing /programming concurrent programs. Remember that in Java all operations that are intrusive in another thread’s execution are deprecated (e.g. stop()).
Write Java program to create deadlock in Java and fix it ?
In java, a deadlock is a situation where minimum two threads are holding lock on some different resource, and both are waiting for other resource to complete its task. And, none is able to leave the lock on resource it is holding.
Read More: Writing a deadlock and resolving in java
No comments:
Post a Comment