According to what I understood, when I use a synchronized block it acquires the lock on an object and releases it when the code block is done executing. In the following code
public class WaitAndNotify extends Thread{
long sum;
public static void main(String[] args) {
WaitAndNotify wan = new WaitAndNotify();
//wan.start();
synchronized(wan){
try {
wan.wait();
} catch (InterruptedException ex) {
Logger.getLogger(WaitAndNotify.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Sum is : " + wan.sum);
}
}
#Override
public void run(){
synchronized(this){
for(int i=0; i<1000000; i++){
sum = sum + i;
}
notify();
}
}
}
what happens if the synchronized block inside the run method acquires the lock first? Then the synchronized block inside the main method has to wait (not because of the wait(), because the other thread acquired the lock). After the run method is done executing, won't the main method enter its synchronized block and wait for a notify which it will never get? What did I misunderstand here?
wait() implicitly exits the respective monitor temporarily and re-enters it upon returning:
See wait()
The current thread must own this object's monitor. The thread releases
ownership of this monitor and waits until another thread notifies
threads waiting on this object's monitor to wake up either through a
call to the notify method or the notifyAll method. The thread then
waits until it can re-obtain ownership of the monitor and resumes
execution.
That's why and how this sort of synchronization does work at all.
Yes, it's possible to perform a notify() before a wait() causing a hung thread, so you need to be careful that it can't happen.
For that reason (and others) it's generally better to use the higher level constructs of java.util.concurrent, since they generally give you less possibilities to shoot yourself in the foot.
You won't see the 'waiting forever' issue here, because you are calling the version of wait() with a timeout; so, after 5 seconds it returns even if it doesn't receive a notify. The 'wait forever' version of the wait() call could indeed exhibit the problem you describe.
You've got two threads here: your WaitAndNotify (WAN) thread, and Java's main execution thread. Both are vying for the same lock.
If the WAN thread gets the lock first, the main thread will be blocked. Being in a blocked state is NOT the same as being in a wait state. A thread in the wait state will wait for notification before moving forward. A thread in the blocked state will actively try to get the lock when it becomes available (and keep trying until it does).
Assuming the run method executes normally, it will call notify(), which will have no effect because no other threads are currently in a wait state. Even if there were, WAN still holds the lock until it exits the synchronized block of code. Once WAN exits the block, THEN Java would notify a waiting thread (if there was one, which there is not).
At this point, the main execution thread now obtains the lock (it is no longer blocked) and enters the wait state. Now you've used the version of wait that will wait up to 5000 milliseconds before continuing. If you used the vanilla version (wait()) it would wait forever because no other process would notify it.
Here is a version of the example program changed to introduce a loop that tests a condition variable. This way you avoid bad assumptions about the state of things after a thread re-acquires a lock upon waking from a wait, and there's no order dependence between the two threads:
public class W extends Thread {
long sum;
boolean done;
public static void main(String[] args) throws InterruptedException {
W w = new W();
w.start();
synchronized(w) {
while (!w.done) {
w.wait();
}
// move to within synchronized block so sum
// updated value is required to be visible
System.out.println(w.sum);
}
}
#Override public synchronized void run() {
for (int i = 0; i < 1000000; i++) {
sum += i;
}
done = true;
// no notify required here, see nitpick at end
}
}
It's not sufficient to wait on a notification, for the reason you point out (order dependence, where you're relying on a race condition hoping one thread acquires the monitor before another) as well as for other reasons. For one thing, a thread can wake up from waiting without ever having received a notification, you can't assume that there was a notify call at all.
When a thread waits, it needs to do so in a loop, where in the test on the loop it checks some condition. The other thread should set that condition variable so the first thread can check it. The recommendation that the Oracle tutorial makes is:
Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
Other nitpicks:
As your example is written, the JVM is not required to make the changes to your sum variable visible to the main thread. If you add a synchronized instance method to access the sum variable, or access the sum within a synchronized block, then the main thread will be guaranteed to see the updated value of sum.
Looking at your logging, there is nothing SEVERE about an InterruptedException, it doesn't mean anything went wrong. An InterruptedException is caused when you call interrupt on a thread, setting its interrupt flag, and that thread is either currently waiting or sleeping, or enters a wait or sleep method with the flag still set. In my toy example at the top of this answer I put the exception in the throws clause because I know it's not going to happen.
When the thread terminates it issues a notifyAll that anything waiting on that object will receive (again, that's how join is implemented). It's better style to use Runnable instead of Thread, partly because of this.
In this particular example it would make more sense to call Thread#join on the summing thread, rather than calling wait.
Here's the example re-written to use join instead:
public class J extends Thread {
private long sum;
synchronized long getSum() {return sum;}
public static void main(String[] args) throws InterruptedException {
J j = new J();
j.start();
j.join();
System.out.println(j.getSum());
}
#Override public synchronized void run() {
for (int i = 0; i < 1000000; i++) {
sum += i;
}
}
}
Thread#join calls wait, locking on the thread object. When the summing thread terminates it sends a notification and sets its isAlive flag to false. Meanwhile in the join method, the main thread is waiting on the summing thread object, it receives the notification, checks the isAlive flag, and realizes it doesn't have to wait anymore, so it can leave the join method and print the result.
Related
Good I have never used threads in java and what happens to me is that I try to call a class and then do something that changes some values of the class, but what happens that changes the values before unfortunately, and I would need to put two threads In java to be able to tell the values that I want to change, wait until the class finishes doing its function, I pass the code and I tell you what I want to do. Thank you.
public void mouseClicked(MouseEvent arg0) {
try {
// capa transparente
if (auxContadorZoom < 3 && auxContadorZoom >= 0) {
zoom.aumentar(100);
for (int i = 0; i < 400; i++) {
for (int j = 0; j < 400; j++) {
image2.setRGB(i, j, zoom.enviar().getRGB(i, j));
}
}
label2.setIcon(new ImageIcon(zoom.enviar()));
label2.removeAll();
label2.add(zoom);
label2.repaint();
auxContadorZoom++;
}
// capa fondo
if (auxContadorZoom1 < 3 && auxContadorZoom1 >= 0) {
zoom1.aumentar(100);
for (int i = 0; i < 400; i++) {
for (int j = 0; j < 400; j++) {
image.setRGB(i, j, zoom1.enviar().getRGB(i, j));
}
}
label.setIcon(new ImageIcon(zoom1.enviar()));
label.removeAll();
label.add(zoom1);
label.repaint();
auxContadorZoom1++;
}
} catch (Exception e) {
// TODO: handle exception
}
//////This is where I want the 2 thread to wait for me to do this so that the zoom class finishes doing its things that I have previously sent
zoom1.activarBoolTrue();
zoom.activarBoolTrue();
}
You should use a ReentrantReadWriteLock
synchronized isn't appropriate since it will have the two threads blocking each other every time they run their code. wait/notify isn't appropriate since it will have the two threads waiting until the GUI event thread runs mouseClicked, which means that your two threads will completely freeze up until someone clicks the relevant GUI element rather than running freely whenever mouseClicked isn't in the special section you want to protect.
Since you want to block the two threads only when the separate GUI event thread calls the mouseClicked method and not have the other two threads blocking each other, a ReentrantReadWriteLock will work nicely.
Implementing it in your example
At the top of the file (just under the package statement if you have one) containing the class that contains the mouseClicked method:
import java.util.concurrent.locks.ReentrantReadWriteLock;
At the top of the class where you are defining variables:
public class … {
public static final ReentrantReadWriteLock mouseClickedLock = new ReentrantReadWriteLock();
In the mouseClicked method when you want to stop the other two threads, lock the writeLock, try to execute your code, then unlock the writeLock:
//////This is where I want the 2 thread to wait for me to do this so that the zoom class finishes doing its things that I have previously sent
mouseClickedLock.writeLock().lock();
try {
zoom1.activarBoolTrue();
zoom.activarBoolTrue();
} finally {
mouseClickedLock.writeLock().unlock();
}
In the two threads, when you're doing something that shouldn't interrupt that special section of the mouseClicked method, lock a readLock, try to execute your code, then unlock that readLock:
mouseClickedLock.readLock().lock();
try {
// Your code here
} finally {
mouseClickedLock.readLock().unlock();
}
Make sure that the code using a read lock doesn't take that long to execute, since it will block mouseClicked's special section until the read lock is unlocked. If a thread has a loop where it does the same thing over and over again, you should probably lock and unlock inside that loop so that it's waiting for one iteration of the loop to complete rather than all iterations.
Now the two threads can do what they want whenever they want to, except when the mouseClicked method's special section is executing, where they will wait until that's finished.
Speed things up with a StampedLock if you start using many more threads
If you begin to have many more threads than just two threads and the GUI event thread, a ReentrantReadWriteLock can become slow. You can use a StampedLock instead to speed things up.
It's a little more complicated to use, since you have to store a long value called a stamp in order to later unlock the StampedLock and since you can't have the same thread lock a StampedLock twice without unlocking it in between the two lockings (i.e., it's not a reentrant lock) or else your program or some of its threads might permanently freeze up.
You can use wait()/notify() which are designed to block (release) a thread until (when) a specific condition is met, or join() which allows one thread to wait until another thread completes its execution.
A possible solution would be sharing a common lock between two threads, say for example Thread-A and Thread-B. After some processing in Thread-A, call wait() on a shared lock and thus Thread-A is waiting. When Thread-B finishes its calculation, call notifyAll() on the same lock, and thus Thread-A resumes its processing.
final Object lock = new Object();
Thread-A
boolean isWorkDone = false;
// Do some processing here!
synchronized (lock) {
try {
while (!isWorkDone) {
lock.wait(); // Thread-A waits here
}
isWorkDone = true;
}
catch (Exception e) {
e.printStackTrace();
}
}
// Do rest of the processing here!
Thread-B
// Do your processing here.
synchronized (lock) {
lock.notifyAll(); // notify Thread-A that processing is done!
}
Have you heard about locks? You need to synchronize on a lock.
Create a lock object with new Object(), like:
Object lock = new Object();
and then use synchronized around code sections that should wait for each other, like:
synchronized (lock) {
…
}
Make sure the threads can have access to that lock object.
Also, you can use a thread's join method to wait for that thread to finish.
I'm learning for OCJP and now I'm at "Thread" chapter, I have some questions about wait and notify methods. I think I understand what's happening here but I just want to make sure that I'm on the right way.I wrote this code as an example:
package threads;
public class Main {
static Object lock = new Object();
public static void main(String[] args) {
new Main().new FirstThread().start();
new Main().new SecondThread().start();
}
class FirstThread extends Thread {
public void run() {
synchronized (lock) {
lock.notify();
System.out.println("I've entered in FirstThread");
}
}
}
class SecondThread extends Thread {
public void run() {
synchronized (lock) {
try {
lock.wait();
System.out.println("I'm in the second thread");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
In this example the console output is I've entered in FirstThread, because the first thread starts, the notify() method is called, then the second thread starts, the wait() method is called and the String "I'm in the second thread" is not printed.
The next scenario is that I reverse the positions of new Main().new FirstThread().start(); and new Main().new SecondThread().start(); the output is
I've entered in FirstThread
I'm in the second thread
because the second thread starts, the wait() method is called, then the first thread starts, the method notify() is called, the console prints I've entered in FirstThread, the wait is released and I'm in the second thread is printed in the console.
Is that happening because the computer is so fast and the threads run sequentially? Theoretically the second start() method can be called first in my opinion is it?.
And the last question I have, is why the lock Object must be static, because if I remove the static modifier the output is always I've entered in FirstThread?
I know that static fields are loaded in JVM when the class is loaded, but I can't understand the logic of lock Object.
The threads are started sequentially, and in theory thread 1 would execute before thread 2, although it's not guaranteed (pretty sure it'll be consistent in this simple case though, as there are no real or simulated aleatory delays).
This is why when thread 2 is started slightly before, it has a chance to wait on a lock that gets notified (by thread 1) subsequently, instead of waiting forever for a lock that's already been notified once (hence, no printing).
On the static lock Object: you're binding your [First/Second]Thread nested classes to instances of Main, so the lock has to be common to both if you want them to synchronize on the same lock.
If it was an instance object, your threads would access and synchronize on a different lock, as your new Main()... idiom would get two instances of Main and subsequently two instances of lock.
"Is that happening because the computer is so fast and the threads run
sequentially? Theoretically the second start() method can be called
first in my opinion is it?. "
Yes, you can introduce a sleep() with random time, for better (unit-) test, or demonstration purpose. (Of course, the final running code should not have that sleep)
And the last question I have, is why the lock Object must be static
Principally, it does not matter whether the lock is static or not, but you have to have the possibility to access it, and it must be the same lock object. (Not one object instance for each class). In your case it must be static, otherwise it would be two different objects instances.
This is wrong because it doesn't change any shared state that the other thread can test:
synchronized (lock) {
lock.notify();
System.out.println("I've entered in FirstThread");
}
And this is wrong because it does not test anything:
synchronized (lock) {
lock.wait();
System.out.println("I'm in the second thread");
}
The problem is, lock.notify() does not do anything at all if there is no thread sleeping in lock.wait(). In your program, it is possible for the FirstThread to call notify() before the SecondThread calls wait(). The wait() call will never return in that case because the notify() call will do nothing in that case.
There's a reason why they make you enter a mutex (i.e., a synchronized block) before you can call wait() or notify(). It's because you are supposed to use the mutex to protect the shared shared state for which the waiter is waiting.
"shared state" can be as simple as a single boolean:
boolean firstThreadRan = false;
The notifier (a.k.a., "producer") does this:
synchronized(lock) {
firstThreadRan = true;
lock.notify();
...
}
The waiter (a.k.a., "consumer") does this:
synchronized(lock) {
while (! firstThreadRan) {
lock.wait();
}
...
}
The while loop is not strictly necessary in this case, but it becomes very important when more than one consumer is competing for the same event. It's good practice to always use a loop.
See https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html for a tutorial that explains wait() and notify() in more detail.
Suppose that I have an arraylist called myList of threads all of which are created with an instance of the class myRunnable implementing the Runnable interface, that is, all the threads share the same code to execute in the run() method of myRunnable. Now suppose that I have another single thread called singleThread that is created with an instance of the class otherRunnable implementing the Runnable interface.
The synchornization challenge I have to resolve for these threads is the following: I need all of the threads in myList to execute their code until certain point. Once reached this point, they shoud sleep. Once all and only all of the threads in myList are sleeping, then singleThread should be awakened (singleThread was already asleep). Then singleThread execute its own stuff, and when it is done, it should sleep and all the threads in myList should be awakened. Imagine that the codes are wrapped in while(true)'s, so this process must happen again and again.
Here is an example of the situation I've just described including an attempt of solving the synchronization problem:
class myRunnable extends Runnable
{
public static final Object lock = new Object();
static int count = 0;
#override
run()
{
while(true)
{
//do stuff
barrier();
//do stuff
}
}
void barrier()
{
try {
synchronized(lock) {
count++;
if (count == Program.myList.size()) {
count = 0;
synchronized(otherRunnable.lock) {
otherRunnable.lock.notify();
}
}
lock.wait();
}
} catch (InterruptedException ex) {}
}
}
class otherRunnable extend Runnable
{
public static final Object lock = new Object();
#override
run()
{
while(true)
{
try {
synchronized(lock) {
lock.wait();
} catch (InterruptedException ex) {}
// do stuff
try {
synchronized(myRunnable.lock) {
myRunnable.notifyAll();
}
}
}
}
class Program
{
public static ArrayList<Thread> myList;
public static void main (string[] args)
{
myList = new ArrayList<Thread>();
for(int i = 0; i < 10; i++)
{
myList.add(new Thread(new myRunnable()));
myList.get(i).start();
}
new Thread(new OtherRunnable()).start();
}
}
Basically my idea is to use a counter to make sure that threads in myList just wait except the last thread incrementing the counter, which resets the counter to 0, wakes up singleThread by notifying to its lock, and then this last thread goes to sleep as well by waiting to myRunnable.lock. In a more abstract level, my approach is to use some sort of barrier for threads in myList to stop their execution in a critical point, then the last thread hitting the barrier wakes up singleThread and goes to sleep as well, then singleThread makes its stuff and when finished, it wakes up all the threads in the barrier so they can continue again.
My problem is that there is a flaw in my logic (probably there are more). When the last thread hitting the barrier notifies otherRunnable.lock, there is a chance that an immediate context switch could occur, giving the cpu to singleThread, before the last thread could execute its wait on myRunnable.lock (and going to sleep). Then singleThread would execute all its stuff, would execute notifyAll on myRunnable.lock, and all the threads in myList would be awakened except the last thread hitting the barrier because it has not yet executed its wait command. Then, all those threads would do their stuff again and would hit the barrier again, but the count would never be equal to myList.size() because the last thread mentioned earlier would be eventually scheduled again and would execute wait. singleThread in turn would also execute wait in its first line, and as a result we have a deadlock, with everybody sleeping.
So my question is: what would be a good way to synchronize these threads in order to achieve the desired behaviour described before but at the same time in a way safe of deadlocks??
Based on your comment, sounds like a CyclicBarrier would fit your need exactly. From the docs (emphasis mine):
A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
Unfortunately, I haven't used them myself, so I can't give you specific pointers on them. I think the basic idea is you construct your barrier using the two-argument constructor with the barrierAction. Have your n threads await() on this barrier after this task is done, after which barrierAction is executed, after which the n threads will continue.
From the javadoc for CyclicBarrier#await():
If the current thread is the last thread to arrive, and a non-null barrier action was supplied in the constructor, then the current thread runs the action before allowing the other threads to continue. If an exception occurs during the barrier action then that exception will be propagated in the current thread and the barrier is placed in the broken state.
I need to know how wait() and notify() works exactly? I couldn't achieve its working by using wait() and notify() as such. Instead if I use a while() loop for wait, it works properly. How is it so? Why can't I use just wait() and notify() simply?
have you read the documentation of the wait-notify functions ?
anyway, for the best way to achieve a wait-notify mechanism, use something like this (based on this website) :
public class WaitNotifier {
private final Object monitoredObject = new Object();
private boolean wasSignalled = false;
/**
* waits till another thread has called doNotify (or if this thread was interrupted), or don't if was already
* notified before
*/
public void doWait() {
synchronized (monitoredObject) {
while (!wasSignalled) {
try {
monitoredObject.wait();
} catch (final InterruptedException e) {
break;
}
}
wasSignalled = false;
}
}
/**
* notifies the waiting thread . will notify it even if it's not waiting yet
*/
public void doNotify() {
synchronized (monitoredObject) {
wasSignalled = true;
monitoredObject.notify();
}
}
}
do note, that each instance of this class should be used only once, so you might want to change it if you need to use it multiple times.
wait() and notify() are used in synchronized block while using threads to suspend and resume where left off.
Wait immediately looses the lock, whereas Nofity will leave the lock only when the ending bracket is encountered.
You can also refer this sample example:
public class MyThread implements Runnable {
public synchronized void waitTest() {
System.out.println("Before Wait");
wait();
System.out.println("After Wait");
}
public synchronized void notifyTest() {
System.out.println("Before Notify");
notify();
System.out.println("After Notify");
}
}
public class Test {
public static void main(String[] args) {
Thread t = new Thread(new MyThread());
t.start();
}
}
I think you are asking why does it work with while loop and does not without.
The answer is when your program calls wait() the operation system suspends your thread and activates (starts) another, and there will happen so called context switch.When OS suspend a thread it needs to save some "meta data" about your thread in order to be able to resume that thread later, PC register is what will answer your question.Basically PC (Program Counter) is a pointer to next instruction which the thread should do or is going to do, after being resumed a thread uses it to understand which instruction it was going to do when OS suspended him, and continues by that instruction (in this case, if you want to look at it by the means of Java program, the next instruction will be the next line after call to wait()).As written in "Java Concurrency in Practice"
Every call to wait is implicitly associated with a specific condition predicate. When calling wait regarding a particular
condition predicate, the caller must already hold the lock associated with the condition queue, and that lock must also
guard the state variables from which the condition predicate is composed.
Because your thread waits because some condition was not met (it should be) after returning to the method that it was suspended in, it needs to recheck that condition to see is it met yet.If condition is met it will not wait anymore, if it's not met it will call wait() again ( as it is in while loop).The important thing to know here is
PC (Program Counter) concept
and
The fact that a Thread that calls wait() on your method will not exit the method -> wait -> get resumed again -> call the method again, instead it will wait -> get resumed again -> continue from the point (instruction/line) where it was suspended (called wait())
Refer below code
public void acquire(){
synchronized(a){
print("acquire()");
try{
//Thread.sleep(5000);
synchronized(this){
wait(5000);
}
print("I have awoken");
print("" + a);
}catch(Exception e){
e.printStackTrace();
}
}
print("Leaving acquire()");
}
public void modify(int n){
print("Entered in modfy");
synchronized(a){
try{
//Thread.sleep(5000);
synchronized(this){
wait(5000);
}
this.a=n;
print("new value" + a);
}catch(Exception e){
e.printStackTrace();
}
}
}
And
final SynchoTest ttObj = new SynchoTest();
Thread A = new Thread(new Runnable(){
public void run() {
ttObj.acquire();
}
},"A");
Thread B = new Thread(new Runnable(){
public void run() {
ttObj.modify(97);
}
},"B");
A.start();
B.start();
As i know about wait(n), it pauses a thread until notify()/notifyAll() get called or the specified time n is over.
But...
In above methods if I directly use wait(n) as I used Thread.sleep(n),
I get runtime exception.
If I synchronize both methods instead of surrounding wait(n) with
synchronized block then I am not getting any exception but both
threads get blocked forever.
But if I do like I attached ie wait(n) surrounding with synchronized
block, it is working fine.
Please tell me why? Also tell me why is it not behaving different on positioning synchronized block if I use sleep(n) instead of wait(n)?
My question is about various result of wait(n) on various position of synchronized keyword.
#Gray
notify() or notifyAll(), and wait() must be in a synchronized block
for the object you are waiting on
explained me why I was getting run time exception by positioning synchronized block on various position.
Now please explain me, why
public void method(){
synchronized(a){
synchronized(this){
wait(n);
}
}
}
is working fine. But
public synchronized void method(){
synchronized(a){
wait(n);
}
}
is blocking my thread forever.
wait(n) and sleep(n) are completely different methods for pausing the execution of code:
wait(n) is called on an Object instance and will pause execution until the notify()/notifyAll() method is called on that instance or until the timer (the parameter) expires.
sleep(n) is called on a Thread object and essentially stops the world as far as that thread is concerned.
What your question comes down to is:
Do you want your object to act as a mutex, waiting for another piece of code to complete before continuing on it's own? Then use wait(n) with a corresponding notify()/notifyAll() in the other code.
Do you want to stop execution of the whole thread for a given timeframe? Then use Thread.sleep(n).
Maybe your code is not working because you didn't call start() on your threads? After you instantiate your threads you need to:
A.start();
B.start();
Also, you cannot do something like the following pattern. You cannot synchronize on a and then change the object of a. Well you can do it but I doubt that's what you want. Basically the a would change and someone else locking on a would lock on another object so would be able to be in the synchronized block as well. Very bad pattern.
synchronized (a) {
...
// not good
this.a = n;
}
Also, if you are not joining with the threads, then the main thread is going to continue on and not wait for A and B to finish. The JVM will wait for them to finish however since they are not daemon threads. And you have no guarantee that A will be called before B so the modify and acquire can happen in any order.
The difference between sleep(5000) and wait(5000) is that the wait can also be awoken by a call to notify() or notifyAll(), and wait() must be in a synchronized block for the object you are waiting on. synchronized also causes a memory barrier to be crossed which synchronizes the storage between multiple threads. It is more expensive because of that but in your case since you look to be sharing this.a then the memory barrier is required.
It is nothing about positioning synchronized keyword. You are facing problem since you locking other object and try to wait for another. Well #Gray has already been explained it, so not repeating it.
For your another problem, regarding why both threads are getting blocked;
Thread A: locks this [A: Runnable]
Thread A: locks a [A: Runnable]
Thread B: waiting for this [A: Runnable, B:BLOCKED]
Thread A: release this (meets wait) [A: TIMED WAITING, B:BLOCKED]
Thread B: lock this [A: TIMED WAITING, B: Runnable]
Thread B: waiting for a which is already locked by thread A [A: TIMED WAITING, B:BLOCKED]
Thread A: waiting for this which is locked by thread B [A: BLOCKED, B:BLOCKED]