Java thread synchronized, Lock, Condition, java thread synchronized
java.util.concurrent.lockInLockThe Framework is an abstraction of locking. It allows the implementation of locking as a Java class, rather than as a language feature. This isLockMultiple implementations leave space. Different implementations may have different scheduling algorithms, performance characteristics, or locking semantics.
ReentrantLockClassLock, It hassynchronizedSame concurrency and memory semantics, but added a similarLock Voting,Timed lock waitAndInterrupted lock wait. In addition, it providesBetter performance. (In other words, when many threads want to access shared resources, JVM can spend less time scheduling threads and spend more time on execution threads .)
- Class Lock lock = ReentrantLock ();
- Output (String name ){
- {
- (I =; I <name. length (); I ++ ){
- {
- }
Differences:
It should be noted that the Lock is automatically released after the code is executed using the sychronized modification method or statement block, but the Lock requires usManually release the lockSo in order to ensure that the lock is finally released (in case of exceptions), put the mutex in try and release the lock in finally !!
3. read/write lock ReadWriteLock
The above example shows the same features as synchronized. What are the advantages of Lock?
Free member Network
For example, a class provides the get () and set () methods for its internal shared data. If synchronized is used, the Code is as follows:
- Class data;
- Set (data ){
- );
- {
- );
- (InterruptedException e ){
- . Data = data;
- +. Data );
- Get (){
- );
- {
- );
- (InterruptedException e ){
- +. Data );
- }
Free member Network
Then write a test class to read and write the shared data using multiple threads:
- Public main (String [] args ){
- // Final Data data = new Data (); syncData data = syncData ();
- // Final RwLockData data = new RwLockData ();
- (I =; I <; I ++ ){
- Thread (Runnable (){
- Run (){
- (J =; j <; j ++ ){
- Random (). nextInt ());
- + I );
- (I =; I <; I ++ ){
- Thread (Runnable (){
- Run (){
- (J =; j <; j ++ ){
- + I );
- }