Java Threads: Locks

Source: Internet
Author: User

First, the principle of the lock

Each object in Java has a built-in lock that automatically obtains a lock on the current instance (this instance) of the code class being executed when the program runs to a non-static synchronized synchronization method. Acquiring a lock on an object is also known as acquiring a lock, locking an object, locking on an object, or synchronizing on an object.

The object lock does not work when the program runs to the synchronized synchronization method or code block. An object has only one lock. So one thread obtains that, no other thread obtains it until the first thread releases (or returns) a lock. This also means that no other thread can enter the synchronized method or block of code on the object until the lock is freed. A release lock is a lock thread that exits the synchronized synchronization method or code block.

2. Precautions

1) You can only synchronize methods, and you cannot synchronize variables and classes.

2) Each object has only one lock, so it should be clear which object to synchronize on.

3) You do not have to synchronize all the methods of the class, and the class can have both synchronous and non-synchronous methods.

4) If you have synchronous and non-synchronous methods, the non-synchronous method can be freely accessed by multiple threads without a lock limit.

5) When the thread sleeps, the lock it holds will not be released.

6) Threads can obtain multiple locks. For example, in the synchronization method of one object to invoke the synchronization method of another object, the synchronization lock of two objects is obtained.

7) Synchronization damage concurrency, you should minimize the range of synchronization. Synchronization can not only synchronize the entire method, but also synchronize some of the code blocks in the method.

8) When using a synchronous block of code, you should indicate which object is synchronized, that is, which object to get the lock, as

1 public int fix (int y) {2      synchronized (this) {3            x=x-y;      }  5 return x;6}    

What happens if a thread can't get a lock?

If a thread attempts to enter a synchronization method and the lock is occupied by another thread, the thread is blocked. In fact, a thread enters a pool of that object and must wait there until it is freed.

When considering clogging, be sure to note which object is being used for locking:

1. A thread that calls a non-static synchronization method with an object will be blocked. If they are different objects, the threads do not interfere with each other.

2. Threads that call a static synchronization method in the same class will be blocked, and they are all locked on the same Cass object.

3. Static synchronization methods and non-static synchronization methods will never block each other, because static methods are locked on the class object, and non-static methods are locked on the object of the class.

4, for the synchronization of the code block, to see what the object has been used to lock (synchronized the contents of the parentheses behind). Threads that synchronize on the same object are blocked and threads on different objects are never blocked.

Third, lock the object

In Java5, the lock object is provided, which can be used to block the resources, and control the concurrent access to the competing resources, which is mainly concentrated in the Java.util.concurrent.locks package, with three interfaces condition, lock, Readewritelock.

1 Condition Interface:2 condition The object monitor method (wait, notify, and Notifyall) into distinct objects to3By combining these objects with any of the lock implementations, you provide multiple wait sets for each object (wait-set). 4 Lock Interface:5 The lock implementation provides a wider range of locking operations than is possible with synchronized methods and statements. 6 Readwritelock Interface:7 Readwritelock maintains a pair of related locks, one for read-only operations and the other for write operations. 8 The following are the necessary steps for a read-write lock:91) Constructs a Reentrantreadwritelock object:Ten             PrivateReentrantreadwritelock rwl=NewReentrantreadwritelock () One2) Extract the Read-write lock: A             PrivateLock readlock=Rwl.readlock () -             PrivateLock writelock=Rwl.writelock () -3) Read locks on all acquisition methods: the              Public Doublegettotalbalance () { - Readlock.lock () -                 Try{...} -                 finally{readlock.unlock ()} +             } -4write locks on all modified methods: +              Public Doubletransfer () { A Writelock.lock () at                 Try{...} -                 finally{writelock.unlock ()} -}

Take a look at a specific example:

  Locktest.java

1  PackageThread;2 3 ImportJava.util.concurrent.ExecutorService;4 Importjava.util.concurrent.Executors;5 ImportJava.util.concurrent.locks.Lock;6 ImportJava.util.concurrent.locks.ReentrantLock;7 8 /*9 * Java thread: LockTen  */ One  Public classLocktest { A      Public Static voidMain (string[] args) { -MyCount mycount=NewMyCount ("955464", 10000);//Create a concurrent access account -Lock lock=NewReentrantlock ();//Create a single object theExecutorservice Pool=executors.newcachedthreadpool ();//Create a pool of threads -User1 u1=NewUser1 ("Zhang San", mycount,-4000, lock); -User1 u2=NewUser1 ("John Doe", mycount,6000, lock); -User1 u3=NewUser1 ("Wang er", mycount,-8000, lock); +User1 u4=NewUser1 ("Leper", mycount,800, lock); -         //perform actions for individual users in the thread pool + Pool.execute (U1); A Pool.execute (U2); at Pool.execute (U3); - Pool.execute (U4); -Pool.shutdown ();//Close the thread pool -     } - } - classUser1Implementsrunnable{ in     PrivateString name;//User name -     PrivateMyCount MyCount;//The account to be operated on to     Private intIocash;//the balance of the operation, there is a positive negative +     PrivateLock MyLock;//the lock object required to perform the Operation -User1 (String name,mycount MyCount,intIocash,lock MyLock) { the          This. name=name; *          This. mycount=MyCount; $          This. iocash=Iocash;Panax Notoginseng          This. mylock=MyLock; -     } the      Public voidrun () { +Mylock.lock ();//Get lock ASystem.out.println (name+ "is operating" +mycount+ "account, the amount is:" +iocash+ ", the current amount is:" + theMycount.getcash ());//Perform cash tasks +Mycount.setcash (Mycount.getcash () +Iocash); -System.out.println (name+ "operation" +mycount+ "account success, the amount is:" +iocash+ ", the current amount is:" + $ Mycount.getcash ()); $Mylock.unlock ();//release the lock or else the thread does not have a chance to execute -     } - } the classmycount{ -     PrivateString OID;//AccountWuyi     Private intCash//Balance theMyCount (String OID,intCash) { -          This. oid=OID; Wu          This. cash=Cash; -     } About      PublicString getoid () { $         returnOID; -     } -      Public voidsetoid (String oid) { -          This. oid=OID; A     } +      Public intGetCash () { the         returnCash; -     } $      Public voidSetcash (intCash) { the          This. cash=Cash; the     } the      PublicString toString () { the         return"Mycount{oid=" +oid+ ", cash=" +cash+ "}"; -     } in}
View Code

The result is:

1 Zhang San is operating mycount{oid=955464,cash=10000} account, the amount is:-4000, the current amount is: 100002 Zhang San operation mycount{oid=955464,cash= 6000} account success, the amount is:-4000, the current amount is: 60003 John Doe is operating mycount{oid=955464,cash=6000} account, the amount is: 6000, the current amount is: 60004 John Doe Operation mycount{oid=955464,cash=12000} account success, the amount is: 6000, the current amount is: 120005 Wang ER is operating mycount{oid=955464,cash=12000} account, The amount is:-8000, the current amount is: 120006 Wang er operation mycount{oid=955464,cash=4000} account success, the amount is:-8000, the current amount is: 40007 The leper is operating mycount{oid=955464,cash=4000} account, the amount is: 800, the current amount is: 40008 leper operation mycount{oid=955464,cash=4800} account success, The amount is: 800, the current amount is: 4800
View Code

Java Threads: Locks

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.