Java High concurrency Programming (iii)

Source: Internet
Author: User

Java high concurrency has three pieces of knowledge: Synchronizer: Synchronizer, how to communicate with each other, synchronization, etc. synchronization container: JDK provides a synchronous container, such as Concurrentmap,concurrentlist, Blockqueen, ThreadPool: Thread pool, Executor,java the thread pool provided on top two, a lot of practical problems can be solved.First, ReentrantlockJDK inside provides a new lock, is a manual lock, it is used to replace synchronized, called Reentrantlock, re-enter the lock, in fact synchronized is also reentrant, but this lock is and synchronized is a difference, Reentrantlock is a tool that is often used when writing with a new synchronization method; Review the previous synchronized synchronization:
/*** Reentrantlock is used to replace synchronized * In this example, because M1 lock this, only M1 execution is complete, m2 can execute * Here is the most primitive semantics of review synchronized *@authormashibing*/ Packageyxxy.c_020;ImportJava.util.concurrent.TimeUnit; Public classReentrantLock1 {synchronized voidM1 () { for(inti=0; i<10; i++) {            Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace ();        } System.out.println (i); }            }        synchronized voidm2 () {System.out.println ("M2 ..."); }         Public Static voidMain (string[] args) {ReentrantLock1 RL=NewReentrantLock1 (); NewThread (RL::M1). Start (); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }        NewThread (rl::m2). Start (); }}
View Code

Second, use Reentrantlock to complete the same function

/*** Reentrantlock used to replace synchronized * Use Reentrantlock to do the same function * Note that it must be necessary to have to manually release the lock (important thing to say three times) * If you encounter an exception with a SYN lock, The JVM will automatically release the lock, but lock must release the lock manually, so the lock is released frequently in finally@authormashibing*/ Packageyxxy.c_020;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classReentrantLock2 {lock lock=NewReentrantlock (); voidM1 () {Try{lock.lock ();//synchronized (this)             for(inti = 0; I < 10; i++) {TimeUnit.SECONDS.sleep (1);            System.out.println (i); }        } Catch(interruptedexception e) {e.printstacktrace (); } finally{lock.unlock (); }    }    voidm2 () {lock.lock (); System.out.println ("M2 ...");    Lock.unlock (); }     Public Static voidMain (string[] args) {ReentrantLock2 RL=NewReentrantLock2 (); NewThread (RL::M1). Start (); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }        NewThread (rl::m2). Start (); }}

Third, the Trylock of Renntrantlock:

/*** Reentrantlock can be used to "try to lock" trylock, which cannot be locked, or cannot be locked within a specified time, the thread can decide whether to continue waiting *@authormashibing*/ Packageyxxy.c_020;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classReentrantLock3 {lock lock=NewReentrantlock (); voidM1 () {Try{lock.lock ();  for(inti = 0; I < 10; i++) {TimeUnit.SECONDS.sleep (1);            System.out.println (i); }        } Catch(interruptedexception e) {e.printstacktrace (); } finally{lock.unlock (); }    }    /*** Use Trylock to try to lock, regardless of whether the lock or not, the method will continue to execute * can be based on the return value of Trylock to determine whether the lock * can also specify the time of Trylock, due to the trylock (timing) throws an exception, so pay attention to the UNC Lock's handling must be put in the finally*/    voidm2 () {/*Boolean locked = Lock.trylock ();        System.out.println ("m2 ..." + locked);        if (locked) lock.unlock (); */                BooleanLocked =false; Try{locked= Lock.trylock (5, Timeunit.seconds); System.out.println ("M2 ..." +locked); } Catch(interruptedexception e) {e.printstacktrace (); } finally {            if(Locked) lock.unlock (); }            }     Public Static voidMain (string[] args) {REENTRANTLOCK3 RL=NewReentrantLock3 (); NewThread (RL::M1). Start (); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }        NewThread (rl::m2). Start (); }}
View Code

Console

012345m2 ... false6789
View Code

Iv. lockinterruptibly Methods of Reentrantlock:

/*** Using Reentrantlock can also call the Lockinterruptibly method, you can respond to the thread interrupt method, * can be interrupted during a thread waiting for a lock *@authormashibing*/ Packageyxxy.c_020;ImportJava.util.concurrent.TimeUnit;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;Importjava.util.function.Function; Public classReentrantLock4 { Public Static voidMain (string[] args) {lock lock=NewReentrantlock (); Thread T1=NewThread ((){            Try{lock.lock (); System.out.println ("T1 Start");                TimeUnit.SECONDS.sleep (Integer.max_value); System.out.println ("T1 End"); } Catch(interruptedexception e) {System.out.println ("Interrupted!"); } finally{lock.unlock ();        }        });                T1.start (); Thread T2=NewThread ((){            Try {                //Lock.lock ();Lock.lockinterruptibly ();//can respond to the interrupt () methodSystem.out.println ("T2 start"); } Catch(interruptedexception e) {System.out.println ("Interrupted!"); } finally{lock.unlock ();        }        });                T2.start (); Try{TimeUnit.SECONDS.sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } t2.interrupt (); //interrupts the wait for thread 2            }}

Console

T1 startinterrupted!  "Thread-1" java.lang.IllegalMonitorStateException at    java.util.concurrent.locks.reentrantlock$ Sync.tryrelease (Reentrantlock.java:151)    at Java.util.concurrent.locks.AbstractQueuedSynchronizer.release (Abstractqueuedsynchronizer.java:1261) At    Java.util.concurrent.locks.ReentrantLock.unlock (reentrantlock.java:457) at    yxxy.c_020. reentrantlock4.lambda$1 (reentrantlock4.java:42) at    Java.lang.Thread.run (Thread.java: 745)

T1 thread firmly to get the lock, always sleep will not release, if the T2 thread in the Run method using Lock.lock (), then the T2 thread will always be silly waiting for this lock, can not be interrupted by other threads;

and using the lockinterruptibly () method is can be interrupted, the main thread main call T2.interrupt () to interrupt T2, tell him is not to get this lock, don't wait;

Error is because Lock.unlock () This method error, because all did not get the lock, can not unlock (), is the code problem, should be judged to have a lock, has locked the case only Lock.unlock ();

V. Reentrantlock can also be designated as a fair lock

The default synchronized are all unfair locks;

What is a fair lock, what is an unfair lock, it is assumed that many threads access the same resource at the time of the lock, where a thread a if it gets, he has the lock, the other people can not access, all have to wait; When the lock is released by thread A, So which thread in the rest of the thread gets the lock, it's probably a matter of looking at the thread scheduler's own choice, so it's called a competition lock, which means there's no fairness in the waiting thread, but this is a high efficiency, and the thread scheduler doesn't have to calculate which thread is going to wait longer, So the default synchronized is a non-fair lock, and the fair lock is that who waits long enough to get the lock.
/*** Reentrantlock can also be designated as a fair lock * *@authormashibing*/ Packageyxxy.c_020;ImportJava.util.concurrent.locks.ReentrantLock; Public classReentrantLock5extendsThread {Private StaticReentrantlock lock =NewReentrantlock ();//The argument is true to indicate a fair lock, please compare the output result         Public voidrun () { for(inti=0; i<100; i++) {lock.lock (); Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Get Lock"); }finally{lock.unlock (); }        }    }     Public Static voidMain (string[] args) {REENTRANTLOCK5 RL=NewReentrantLock5 (); Thread Th1=NewThread (RL); Thread Th2=NewThread (RL);        Th1.start ();    Th2.start (); }}

Six

Java High concurrency Programming (iii)

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.