Use of class condition and class Reentrantlock

Source: Internet
Author: User
Tags finally block

First look at a piece of code to achieve the following print effect:

1 2 A 3 4 B 5 6 C 7 8 D 9 E One-page F-G-H-P-I-J (K)-Ten L (33 M) Q-A-R-Notoginseng-S-Max-T-U-V-X-Y

 Packagetest;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classMyThread { Public Static voidMain (string[] args) {lock lock=NewReentrantlock (); Condition Condition1=lock.newcondition (); Condition Condition2=lock.newcondition (); Threada a=NewThreada (lock, Condition1, condition2); THREADB b=Newthreadb (lock, Condition1, condition2);        A.start ();    B.start (); }}classThreadaextendsThread {lock lock;    Condition Condition1;    Condition Condition2;  PublicThreada (lock lock, Condition condition1, Condition condition2) {Super();  This. Lock =lock;  This. Condition1 =Condition1;  This. Condition2 =Condition2; } @Override Public voidrun () {Try{lock.lock ();  for(inti = 1; I <= 52; i++) {                if(i% 2! = 0) {System.out.print (i+ "" + (i + 1));                Condition2.signal (); } Else{condition1.await (); }            }        } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock (); }    }}classThreadbextendsThread {lock lock;    Condition Condition1;    Condition Condition2;  Publicthreadb (lock lock, Condition condition1, Condition condition2) {Super();  This. Lock =Block;  This. Condition1 =Condition1;  This. Condition2 =Condition2; } @Override Public voidrun () {Try{lock.lock ();  for(inti = (int) ' A '; I < (int) (' A ' + 52); i++) {System.out.print (" " + (Char) i + "");                Condition1.signal ();            Condition2.await (); }        } Catch(interruptedexception e) {e.printstacktrace (); } finally{lock.unlock (); }    }}

The above code is an example of how we use class condition and class Reentrantlock in our project, and then we'll elaborate on these concepts.

A simple comparison of synchronized and lock:

Synchronized is a keyword in Java, which is a feature built into the Java language. So why is there lock?

We know that if a block of code is synchronized, when a thread acquires the corresponding lock and executes the block, the other thread waits until the thread that acquires the lock releases the lock, and there are only two cases where the thread that acquires the lock releases the lock:

1) The thread that acquires the lock executes the code block, and then the thread releases the possession of the lock;

2) A thread execution exception occurs when the JVM causes the thread to automatically release the lock.

So if the thread that acquires the lock waits for IO or other reasons (such as calling the Sleep method), the thread that gets the lock is blocked, but the lock is not released, and the other threads can only wait in a dry way, which greatly affects the execution efficiency of the program. There is therefore a need for a mechanism to allow waiting threads to wait indefinitely (for example, to wait for a certain amount of time or to respond to interrupts), which can be done with lock.

Another example: when there are multiple threads reading and writing files, there is a conflict between read and write operations, and write operations and writes conflict, but there is no conflict between read and read operations. but using the Synchronized keyword to achieve synchronization can cause a problem: If multiple threads are simply reading, other threads can only wait for the read operation when one thread is reading. Therefore, a mechanism is needed to enable multiple threads to simply read, and there will be no conflicts between threads, which can be done by lock. Additionally, through lock you can know that the line threads has not been successfully acquired to the lock. This is synchronized can't do.

To summarize, this means that lock provides more functionality than synchronized. But pay attention to the following points:

1) lock is not built into the Java language, synchronized is a keyword in the Java language and is therefore a built-in feature. Lock is an interface that enables simultaneous access through this interface;

2) lock and synchronized a very big difference, the use of synchronized does not require the user to manually release the lock, when the synchronized method or synchronized code block execution, the system will automatically let the thread release the lock on the use of , and lock must be the user to manually release the lock, if there is no active release of the lock, it is possible to cause a deadlock phenomenon.

 public  interface   lock { void   lock ();  void  lockinterruptibly () throws      interruptedexception;     boolean   Trylock ();  boolean  trylock (long  time,    Timeunit unit) throws   interruptedexception;     void   unlock (); Condition newcondition ();}  

In the lock interface, lock (), Trylock (), Trylock (long time, Timeunit unit), and lockinterruptibly () are used to acquire the lock. The UnLock () method is used to release the lock.

First, the lock () method is the most commonly used method, which is used to acquire a lock. Waits if the lock has been fetched by another thread. as mentioned earlier, if you use lock, you must voluntarily release the lock, and the lock will not be released automatically when an exception occurs. Therefore, in general, the use of lock must be done in the try{}catch{} block, and the operation to release the lock is placed in the finally block to ensure that the lock must be released to prevent the occurrence of deadlocks. The use of lock for synchronization is usually done in the following form:

Lock lock = ...; Lock.lock (); Try {    // Processing Task }catch(Exception ex) {     }finally{    Lock.unlock ();    // release Lock }

The second Trylock () method has a return value, which represents the attempt to acquire a lock, returns true if it succeeds, or false if the fetch fails (that is, the lock has been fetched by another thread), which means that the method returns immediately anyway. You won't be waiting there until you get the lock. The Trylock (long time, Timeunit unit) method and the Trylock () method are similar except that the method waits for a certain amount of time when the lock is not reached, and returns False if the lock is not held within the duration of the period. Returns true if the lock was obtained at the beginning or if the lock was obtained during the wait period. Usually this is used:

 lock lock = ...;  if   (Lock.trylock ()) { try  {  Processing task }catch   (Exception ex) {}  finally{Lock.unlock ();       //  release lock   else   { //  If you can't get the lock, do something else } 

The

lockinterruptibly () method is special, and when the lock is acquired by this method, if the thread is waiting for the lock to be acquired, the thread can respond to the interrupt, that is, the wait state of the break thread. It is also said that when two threads pass through lock.lockinterruptibly () to acquire a lock, if thread A acquires a lock at this point, and thread B is only waiting, then the call to thread B of the Threadb.interrupt () method can be used in the wait process of break thread B. because the declaration of lockinterruptibly () throws an exception, so lock.lockinterruptibly () The throw interruptedexception must be declared in a try block or outside the method called lockinterruptibly ().

 Public void throws interruptedexception {    lock.lockinterruptibly ();     Try  {       //.....     }    finally  {        lock.unlock ();    }  }

When a thread acquires a lock, it is not interrupted by the interrupt () method. Calling the interrupt () method alone does not break the thread that is running the process, only the threads in the blocking process. therefore, when a lock is acquired through the lockinterruptibly () method, it can be interrupted if it cannot be obtained and only waits. and with synchronized modification, when a thread waits for a lock, it cannot be interrupted, only waiting.

Summary: The lock () method waits if the lock has been fetched by another thread. The Trylock () method will not wait until the lock is taken. The lockinterruptibly () method responds to interrupts. Reentrantlock, which means "reentrant lock", Reentrantlock is the only class that implements the lock interface, and Reentrantlock provides more methods. The usual methods are as follows.

Reference Address:

[1]http://www.cnblogs.com/dolphin0520/p/3923167.html

Use of class condition and class Reentrantlock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.