Notes [Java7 Concurrent Programming Practical manual]2.5 using lock to achieve synchronization of two

Source: Internet
Author: User

Notes [Java7 Concurrent Programming manual] series catalogue

Profile

Next, practice modifying the fairness of the lock, and the conditions in which it is used.

Modify the fairness of the lock Reentrantlock
    /**     *构造一个锁对象,默认为非公平锁     */    publicReentrantLock(boolean fair) {        newnew NonfairSync();    }

According to the structure of reentrantlock, it can be seen that the default is to construct a non-fair lock;

What is the difference between a fair lock and a non-fair lock
    1. Fair Lock: There are multiple threads concurrently accessing the critical section of the Fair lock, which waits for the last lock release lock to be chosen by a thread to acquire the lock (the policy is to select a CLH to access the critical section at the time of the longest wait)
    2. Non-fair Lock: no conditional constraints
    3. Fair and unfair policies apply only to the lock () and Unlock () methods. While the Trylock method of the lock interface does not put the thread into hibernation, the Fair property does not affect this method.

For detailed explanation, please refer to the Java Multithreading Series – "Juc lock" 03 Fair Lock (One)

Example demonstrates fairness policy

Write a printing method. There are two critical sections in which the second critical section waits for the lock to be tested when the front thread is executed. To see the effect.

 Public  class Client {     Public Static void Main(string[] args)throwsinterruptedexception {FinalFairsyncdemo FSD =NewFairsyncdemo (); thread[] arr =Newthread[Ten]; for(inti =0; I <Ten; i++) {Arr[i] =NewThread (NewRunnable () {@Override                 Public void Run() {fsd.print ();        }            }); } for(inti =0; i < arr.length; i++) {Arr[i].start (); Thread.Sleep ( -);//Let thread start time increase. Let the fair lock to choose who waits the longest}}}class Fairsyncdemo {PrivateReentrantlock lock =NewReentrantlock (true);//Construction of Fair lock     Public void Print() {lock.lock (); Long time = (Long) (Math.random () * +); System.out.println (Thread.CurrentThread (). GetName () +", Printing time-consuming"+ Time +"milliseconds");Try{Thread.Sleep (time); }Catch(Interruptedexception e)        {E.printstacktrace ();        } lock.unlock ();        Lock.lock (); Long time2 = (Long) (Math.random () * +); System.out.println (Thread.CurrentThread (). GetName () +", STP2 printing time-consuming"+ time2 +"milliseconds");Try{Thread.Sleep (time); }Catch(Interruptedexception e)        {E.printstacktrace ();    } lock.unlock (); }}

The result of a run:

thread-0, printing time-consuming821Ms Thread-1, printing time-consuming atMs Thread-2, printing time-consuming +Ms Thread-3, printing time-consuming455Ms Thread-4, printing time-consuming951Ms Thread-5, printing time-consuming857Ms Thread-6, printing time-consuming680Ms Thread-7, printing time-consuming $Ms Thread-8, printing time-consuming theMs Thread-0, STP2 printing time-consuming107Ms Thread-1, STP2 printing time-consuming960Ms Thread-2, STP2 printing time-consuming598Ms Thread-9, printing time-consuming236Ms Thread-3, STP2 printing time-consuming969Ms Thread-4, STP2 printing time-consuming774Ms Thread-5, STP2 printing time-consuming657Ms Thread-6, STP2 printing time-consuming766Ms Thread-7, STP2 printing time-consuming theMs Thread-8, STP2 printing time-consuming782Ms Thread-9, STP2 printing time-consuming745Milliseconds

Result Description:
When we start 10 threads, each thread starts, sleeps 100 milliseconds,
From Thread-0, printing takes 821 milliseconds to THREAD-0,STP2 print time of 107 milliseconds, during this period. The time that STP2 waits is the time that thread 1-8 runs, and the wait time is probably more than 3,000 milliseconds. (One of the strategies here is not clear to me) so I was chosen by the fair policy to continue executing the critical section code.

The following result is a result of the operation of the non-fair lock:
Change to unfair lock: private reentrantlock lock = new Reentrantlock (false); Construct Fair Lock

thread-0, printing time-consuming178Ms Thread-0, STP2 printing time-consuming492Ms Thread-1, printing time-consuming534Ms Thread-1, STP2 printing time-consuming951Ms Thread-2, printing time-consuming422Ms Thread-2, STP2 printing time-consuming882Ms Thread-3, printing time-consuming353Ms Thread-3, STP2 printing time-consuming487Ms Thread-4, printing time-consuming theMs Thread-4, STP2 printing time-consuming AboutMs Thread-5, printing time-consuming theMs Thread-5, STP2 printing time-consuming -Ms Thread-6, printing time-consuming568Ms Thread-7, printing time-consuming676Ms Thread-7, STP2 printing time-consuming -Ms Thread-8, printing time-consuming511Ms Thread-8, STP2 printing time-consuming998Ms Thread-9, printing time-consuming171Ms Thread-9, STP2 printing time-consuming425Ms Thread-6, STP2 printing time-consuming theMilliseconds

Result Description:
It is obvious that there is a difference between fairness and the effect of flying fairness.

Using multi-condition condition in locks

The conditions associated with it are provided in lock, and a lock may be associated with one or more conditions, which are declared through the condition interface. The purpose is to run the thread to acquire the lock and to see if a condition is satisfied if it is not met, pending until a thread wakes them up. The condition interface provides a mechanism for suspending threads and invoking threads;

Example demonstrating the use of conditions

OK, let's describe what the following heap of code does: use 5 threads to set (produce) a value, use 5 threads to remove (consume) this value;
Use condition in Add and Remoe instead of the wait operation for monitor locks. And wake-up operations.

It is worth noting that:
1. Condemo this inner class modified to con start throws an error exception that cannot be found for the class (do not know if con is a keyword or what the reason)
2. Number of read and write threads if not, the deadlock will occur.
3. All conditions condition must use the peer lock object to create the Lock.newcondition ();
4. The condition must be used between the lock () and the Unlock () method.
5. In determining whether the condition is satisfied, need to determine in the cycle, not meet the conditions can not leave the loop body, otherwise the data will not get the results we want
6. Calling the await () method into the dormant thread may be interrupted, so the interruptedexception exception must be handled

 Public  class Client {     Public Static void Main(string[] args)throwsinterruptedexception {FinalCondemo con =NewCondemo (); for(inti =0; I <5; i++) {NewThread (NewRunnable () {@Override                 Public void Run() {con.add ();        }}). Start (); } for(inti =0; I <5; i++) {NewThread (NewRunnable () {@Override                 Public void Run() {con.remove ();        }}). Start (); }}}class Condemo {PrivateReentrantlock lock =NewReentrantlock ();//Construction lock    PrivateLong Depot =NULL;//acts as a repository, and when there is a value, it is removed and set to null. Represents being taken away, waiting for add a number    PrivateCondition Removecon;PrivateCondition Addcon; Public Condemo() { This. Removecon = Lock.newcondition (); This. Addcon = Lock.newcondition (); }/** * Set * * *     Public void Add() {lock.lock ();Try{ while(Depot! =NULL) {//have value, then wait to be taken away. And then set the valueAddcon.await ();//Let current thread operation wait} depot = (Long) (Math.random () * +); System.out.println (Thread.CurrentThread (). GetName () +",----set up:"+ depot);//wake-up condition to allow the thread to wait for the value to take actionRemovecon.signalall (); }Catch(Interruptedexception e)        {E.printstacktrace (); }finally{Lock.unlock (); }    }/** * The number of removal settings * /     Public void Remove() {lock.lock ();Try{ while(Depot = =NULL) {//No value is desirable, let the condition waitRemovecon.await ();//Let remove operation wait} System.out.println (Thread.CurrentThread (). GetName () +"and took away:"+ depot); Depot =NULL;//wake-up condition, let's wait for the thread to set the value. Set the value quicklyAddcon.signalall (); }Catch(Interruptedexception e)        {E.printstacktrace (); }finally{Lock.unlock (); }    }}

The result of a run:

Thread-2,----设置了:274Thread-8,拿走了:274Thread-1,----设置了:358Thread-5,拿走了:358Thread-0,----设置了:407Thread-7,拿走了:407Thread-3,----设置了:761Thread-9,拿走了:761Thread-4,----设置了:250Thread-6,拿走了:250

The result shows: can see the above result: have value, can be taken away, be taken away, can be produced a value.

Other apiawait in condition (long time, timeunit unit)
boolean await(longthrows InterruptedException;

The thread will remain dormant until one of the following conditions is used:
1. One other thread interrupts the current thread
2. Another thread invokes the Singal () or Singalall () method of the condition that suspends the current thread
3. The specified wait time has passed

Awaituninterruptibly ()
它是不可中断的。这个线程将休眠直到其他某个线程调用了将他挂起的条件的singal()或则signalAll()方法。
Awaituntil (date date)

The thread will remain dormant until one of the following conditions occurs.
1. One other thread interrupts the current thread
2. One of the other threads called the Dingal () or Signalall () method of the condition on which he was suspended
3. The specified deadline has arrived.

You can also use a condition with a read-write lock.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Notes [Java7 Concurrent Programming Practical manual]2.5 using lock to achieve synchronization of two

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.