Lock locks for producer - consumer model

Lock Lock Description:

You can use synchronized in java to access the next multi-thread synchronization object, in order to obtain a more flexible usage scenarios, efficient performance, java also offers Lock interface and its implementation class ReentrantLock and read-write locks ReentrantReadWriteLock.

 Compared synchronized to achieve synchronization, use the Lock synchronization are the following differences:

 1, the use of synchronized keyword, and release the lock control start and end positions is synchronized in the synchronization code block. When using the synchronization Lock, the lock can be acquired and released in different code blocks, a different approach. This is based on the characteristics of the user to manually obtain and release the lock.

 2, Lock interface provides tries to acquire a lock tryLock () method returns false when calling tryLock () to acquire the lock fails, this thread can perform other operations that the thread will not go to sleep. tryLock () method can be passed a long time parameter type, allowing a certain time to acquire lock.

 3, Lock implementation class ReentrantReadWriteLock interface provides read and write locks allow multiple threads to obtain read locks, but only one thread acquires the write lock. Read and write locks can not be obtained. To achieve the separation of reading and writing, which is very important in applications that require concurrent read, as lucene allows multiple threads to read the index data query but there is only one thread is responsible for building the index data.

 4, the above three points, to achieve synchronization Lock with better performance.

Lock locks and condition synchronization:

And synchronized Similarly, Lock lock condition synchronization can also be achieved. Providing interface Condition java package and the concurrent implementation class ConditionObject.

When certain conditions are met, the call Condition await () method makes the current thread to sleep to wait. Call the Condition of signalAll () method because the thread wake await () goes to sleep.

In synchronized with the condition synchronization Bowen, we use synchronized implemented a producer - consumer model, here, to try to use Lock locks and synchronization to achieve the same conditions of a producer - consumer model:

 

[java]  view plain copy print ?
  1. public class MessageStorageByLock {  
  2.     private int maxSize;  
  3.     private List<String> messages;  
  4.   
  5.     private final ReentrantLock lock;  
  6.     Private  Final for condition Condition conditionWrite; // declare two locks conditions  
  7.     private final Condition conditionRead;  
  8.     public MessageStorageByLock(int maxSize) {  
  9.         this.maxSize = maxSize;  
  10.         messages = new LinkedList<String>();  
  11.         = Lock  new new of ReentrantLock ( true); // true fairness modify locks, to true, using lifo order to acquire the lock queue  
  12.         = lock.newCondition conditionWrite (); // call newCondition () method, i.e. new ConditionObject ();  
  13.         conditionRead = lock.newCondition();  
  14.   
  15.     }  
  16.     public void set(String message){  
  17.         // use locks to synchronize, access to operating income, when the lock is being used by another thread, the current thread will go to sleep  
  18.         lock.lock();  
  19.         try{  
  20.             while(messages.size() == maxSize){  
  21.                     System.out.print("the message buffer is full now,start into wait()\n");  
  22.                     conditionWrite.await (); // When the condition is satisfied thread sleeps and release the lock. When you call signalAll (). Thread wake up and regain lock  
  23.             }  
  24.             Thread.sleep(100);  
  25.             messages.add(message);  
  26.             System.out.print("add message:"+message+" success\n");  
  27.             conditionRead.signalAll (); // wake because conditionRead.await () dormant thread  
  28.         }catch (InterruptedException e){  
  29.             e.printStackTrace ();  
  30.         }finally {  
  31.             lock.unlock();  
  32.         }  
  33.     }  
  34.     public String get(){  
  35.         String message = null;  
  36.         lock.lock();  
  37.         try{  
  38.             while(messages.size() == 0){  
  39.                 conditionRead.await();  
  40.                 System.out.print("the message buffer is empty now,start into wait()\n");  
  41.             }  
  42.             Thread.sleep(100);  
  43.             message = ((LinkedList<String>)messages).poll();  
  44.             System.out.print("get message:"+message+" success\n");  
  45.             conditionWrite.signalAll();  
  46.         }catch (InterruptedException e){  
  47.             e.printStackTrace ();  
  48.         }finally {  
  49.             lock.unlock();  
  50.         }  
  51.         return message;  
  52.     }  
  53. }  

to sum up:

 

Whether the synchronized keyword or Lock locks are used to control the synchronization of access to resources in a multithreaded environment, in order to avoid confusion due to multiple threads concurrently read and write data to the data caused. The difference is that with synchronized, Lock lock synchronization needs to obtain and release the lock when the user manually control, its flexibility makes it possible to achieve a more complex multi-thread synchronization and higher performance, but at the same time, the user must acquire a lock after the code in time to catch exceptions during operation of the lock is released and finally block.

Guess you like

Origin www.cnblogs.com/binghuaZhang/p/11119648.html