Home > Back-end >  How do you write Java prevent cache through the lock?
How do you write Java prevent cache through the lock?

Time:04-21

A thread reenterlock trylock succeeded locks,
Thread B reenterlock trylock failed to obtain A lock, I hope I can receive B threads directly wait for best, A thread is the announcement that releases the lock to read cache
This code for how to write?

CodePudding user response:

Thread B reenterlock directly. The lock that he will block until A thread reenterlock release

CodePudding user response:

Public class A (
Thread B
The public A (Thread B) {
This. B=B;
}
The run () {
{if (lock. TryLock ())
Sytem. Out. Println (" business ");
LockSouport. UnPark this. (B)
} the finally {
lock.unlock();
}
}


Public class B (
The run () {
LockSouport. Park ();
{if (lock. TryLock ())
Sytem. Out. Println (" business ");
} the finally {
lock.unlock();
}
}

CodePudding user response:

reference 1st floor baichangda234 response:
B reenterlock directly. The thread lock, he will block until A thread reenterlock release

If two threads of the same class the same method, simple code

CodePudding user response:

A lock can guarantee the synchronous execution of multiple threads, which is A - & gt; B - & gt; A - & gt; B, will never be a concurrent execution
This case directly to reenterlock. Lock, always a thread lock, other threads are waiting
  • Related