Java thread security Lock, java thread lock

Source: Internet
Author: User

Java thread security Lock, java thread lock

Java. util. concurrent. locks

We used the synchronized keyword for thread security. For thread collaboration, we used Object. wait () and Object. Policy (). In JDK1.5, java provides Lock for us to implement the same functions as them, and the performance is superior to them. In JDK1.6, JDK optimizes synchronized, there is little difference between the two methods in performance.

I. Why does lock appear?

Synchronized: the code block modified by synchronized. When a thread acquires the corresponding lock and executes the code block, other threads can only wait until the thread that obtains the lock releases the lock, if it is not released, you need to wait infinitely. The thread that gets the lock releases the lock in two cases:

1. the thread that obtains the lock executes the code block and then releases the lock.

2. If an exception occurs during thread execution, the JVM will allow the thread to automatically release the lock.

Comparison between Lock and synchronized:

1. Lock is not built into the Java language, and synchronized is a keyword of the Java language, so it is a built-in feature. Lock is a class that enables synchronous access.

2. synchronized does not need to manually release the Lock. After the synchronized method or synchronized code block is executed, the system will automatically let the thread release the occupied Lock. The Lock must be manually released, if the lock is not released, a deadlock may occur.

Ii. Common classes and interfaces in the java. util. concurrent. locks package.
Public interface Lock {// used to obtain the Lock. If the lock has been obtained by another thread, wait. Void lock (); // when this method is used to obtain the lock, if the thread is waiting for the lock to be obtained, the thread can respond to the interruption, that is, the waiting status of the interrupt thread void lockInterruptibly () throws InterruptedException; // It indicates to try to obtain the lock. If the acquisition is successful, true is returned. If the acquisition fails (that is, the lock has been obtained by other threads ), returns false boolean tryLock (); // The method is similar to tryLock (), but the difference is that this method will wait for a certain amount of time when the lock is not available, if the lock cannot be obtained within the time limit, false is returned. Returns true if the lock is obtained at the beginning or within the waiting period. Boolean tryLock (long time, TimeUnit unit) throws InterruptedException; // release the lock void unlock (); Condition newCondition ();}

1. Lock and unlock
Lock is used to obtain the Lock, but it does not actively release the Lock, so it must be used with unlock. Generally, you must use the Lock in the try {} catch {} block and put the Lock release operation in the finally block to ensure that the Lock will be released, prevent deadlocks.

Package com. jalja. base. threadTest; import java. util. concurrent. locks. reentrantLock; public class LockTest implements Runnable {public static ReentrantLock lock = new ReentrantLock (); public static int c = 0; public void run () {for (int I = 0; I <1000; I ++) {lock. lock (); // get the lock try {System. out. println (Thread. currentThread (). getName () + "get lock"); System. out. println (Thread. currentThread (). getName () + "===>" + c); c ++;} catch (Exception e) {e. printStackTrace ();} finally {System. out. println (Thread. currentThread (). getName () + "Release lock"); lock. unlock (); // release lock }}public static void main (String [] args) {LockTest lt = new LockTest (); Thread thread1 = new Thread (lt ); thread thread2 = new Thread (lt); thread1.start (); thread2.start (); try {thread1.join (); thread2.join ();} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (c );}}

Note: The same thread can continuously obtain the same lock, but the same number of locks must also be released. Allow the following statement

Lock. lock (); // obtain the lock. lock (); lock. lock (); try {System. out. println (Thread. currentThread (). getName () + "get lock"); System. out. println (Thread. currentThread (). getName () + "===>" + c); c ++;} catch (Exception e) {e. printStackTrace ();} finally {System. out. println (Thread. currentThread (). getName () + "Release lock"); lock. unlock (); // release the lock. unlock (); // release the lock. unlock (); // release the lock}

2. Get the lock wait time tryLock (long time, TimeUnit unit)
If you ask a friend to play basketball, your friend hasn't appeared yet, and you haven't arrived in an hour, I think you will definitely leave. This should also be the case for the thread, because we usually cannot determine why a thread cannot obtain the lock, but we can give the thread a time limit for obtaining the lock, if the lock has not been obtained by the time, discard the lock.

Package com. jalja. base. threadTest; import java. util. concurrent. timeUnit; import java. util. concurrent. locks. reentrantLock; public class TryLockTest implements Runnable {public static ReentrantLock lock = new ReentrantLock (); private static int m = 0; public void run () {try {if (lock. tryLock (1, TimeUnit. SECONDS) {// sets the wait time for obtaining the lock to 1 second. out. println (Thread. currentThread (). getName () + "get lock"); m ++; // Thread. sleep (2000); // set sleep for 2 seconds} else {System. out. println (Thread. currentThread (). getName () + "Unlocked") ;}} catch (Exception e) {e. printStackTrace ();} finally {if (lock. isHeldByCurrentThread () {lock. unlock () ;}} public static void main (String [] args) {TryLockTest thread1 = new TryLockTest (); TryLockTest thread2 = new TryLockTest (); thread th1 = new Thread (thread1); Thread th1 = new Thread (thread2); th1.start (); th2.start (); try {// wait for the main thread to wait until the execution of the th1.join (); th2.join ();} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (m );}}

Execution result:

Thread-0 get lock Thread-1 get lock 2

This Code allows the thread to wait for a maximum of 1 second in the lock request. If the lock is not obtained for more than one second, false is returned. If the lock is obtained, true is returned, according to the execution result, we can see that the Thread-1 gets the lock within 1 second.

We enable the annotation // Thread. sleep (2000); you will find that one of Thread-1 or Thread-0 must be unobtained because the Thread occupying the lock takes 2 seconds, the waiting time of the lock thread is 1 second, so it gave up the request Lock operation immediately after 1 second.

 

Related Article

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.