Module - IV Java
Module - IV Java
Multi Threading
No, when a thread is terminated or moves into dead state, it cannot alive again. If
we try to it by calling start() method, we will get
an IllegalThreadStateException exception.
Why is stop method deprecated in
Java?
• In the early days of Java, Thread class defined a stop() method that
simply terminates a thread. But later on Java 1.2 version, stop()
method had been deprecated. This is because this method is
“inherently unsafe” and can cause serious problem sometimes.
Therefore, it should not be used in the program for thread safety.
• An interviewer can ask you an interesting question that what logic
will you use to stop a thread in the place of stop() method because
stop() method had been deprecated from Java 1.2.
• Basically, there are two ways through which we can easily stop a
thread in java program. They are:
• 1. By using boolean variable.
2. By using isInterrupted() method
Thread.sleep() Method
[welcome]
[new]
[programmer]
Difference between synchronized
keyword and synchronized block
• When we use synchronized keyword with a method, it
acquires a lock in the object for the whole method. It
means that no other thread can use any synchronized
method until the current thread, which has invoked it's
synchronized method, has finished its execution.
• synchronized block acquires a lock in the object only
between parentheses after the synchronized keyword.
This means that no other thread can acquire a lock on
the locked object until the synchronized block exits.
But other threads can access the rest of the code of the
method.
1.Which is more preferred - Synchronized method or
Synchronized block?
In Java, synchronized keyword causes a performance
cost. A synchronized method in Java is very slow and
can degrade performance. So we must use
synchronization keyword in java when it is necessary
else, we should use Java synchronized block that is
used for synchronizing critical section only.
2. Can we synchronize static method in Java?
Yes, a static method can also be synchronized. In this
case, the lock is placed on the class, not on the object.
The thread will execute the method body only when
the lock is placed on the class. It will hold the lock until
it leaves the method body.
Deadlock in Java