For thread safety we used the Synchronized keyword earlier, and for thread collaboration we used object.wait () and object.notify (). In JDK1.5 Java provides us with lock to achieve the same functionality as they do, and performance outperforms them, and in JDK1.6, the JDK is optimized for synchronized, and the performance gap is small.
First, why do you appear lock
Synchronized-Modified code block, when a thread acquires a corresponding lock and executes the block, the other threads can only wait until the thread that acquires the lock releases the lock and waits indefinitely if it is not released. The thread that acquires the lock releases the lock only in two cases:
1. The thread that acquires the lock executes the code block, and then the thread releases the possession of the lock.
2. The thread execution exception occurs when the JVM causes the thread to automatically release the lock.
Lock vs. Synchronized:
1, lock is not built into the Java language, synchronized is the Java language keyword, so it is built-in features. Lock is a class that enables simultaneous access through this class.
2, synchronized do not need to manually release the lock, when the synchronized method or synchronized code block execution, the system will automatically let the thread release the lock, and lock must be the user to manually release the lock, if there is no active release lock, It is possible to cause a deadlock phenomenon.
second, the class and interface commonly used in Java.util.concurrent.locks package.
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
public interface lock { //is used to acquire locks. Waits if the lock has been fetched by another thread. void lock (); // When a lock is acquired through this method, if the thread is waiting to acquire the lock, the thread can respond to the interrupt. That is, the waiting state of the interrupt thread void lockinterruptibly () throws InterruptedException; //it represents an attempt to acquire a lock, returns true if it succeeds, or returns false boolean if the acquisition fails (that is, the lock has been fetched by another thread) Trylock (); the //and Trylock () methods 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 time period. Returns true if the lock was obtained at the beginning or if the lock was obtained during the wait period. boolean trylock (Long time, timeunit unit) throws interruptedexception; //release lock void unlock (); condition newcondition ();}
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
1. Lock and Unlock
Lock is used to acquire a lock, but it does not actively release the lock and needs to be used in conjunction with unlock (). It is generally necessary to use lock in the try{}catch{} block, and the release lock operation is placed in the finally block to ensure that the lock must be released to prevent the occurrence of deadlocks.
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
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 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); }}
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
Note: The same thread can obtain the same lock continuously, but must also release the same number of locks. Allow the following wording
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
lock.lock ();//Get lock 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 lock lock.unlock ();//Release lock lock.unlock ();//Release lock }
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
2. Get lock Wait Time trylock (long, timeunit unit)
If you ask a friend to play basketball, the appointment time to your friend has not appeared, you wait 1 hours or not, I think you will be disappointed to leave. This is also the case for threads, because usually we cannot tell why a thread cannot get a lock, but we can give the thread a time limit for acquiring the lock, and if the lock is not acquired by the time, then the acquisition lock is discarded.
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
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)) {//Set wait time to get lock 1 seconds system.out.println ( Thread.CurrentThread (). GetName () + "get Lock"); m++; //thread.sleep (2000);//Set sleep 2 seconds }else{ system.out.println (Thread.CurrentThread (). GetName () + "not acquired lock"); } } catch (exception e) { e.printstacktrace (); }finally{ if (Lock.isheldbycurrentthread ()) { lock.unlock (); } } } public static void main (String[] args) { &Nbsp; trylocktest thread1=new trylocktest (); trylocktest thread2=new trylocktest (); thread th1=new thread (THREAD1); thread th2 =new thread (thread2); th1.start (); th2.start (); try { //let the main thread wait for the Th1, Th2 thread to finish executing, and then continue to execute th1.join (); th2.join (); } catch ( Interruptedexception e) { E.printstacktrace (); &nBsp; } system.out.println (M) ; }}
650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>
Execution Result:
Thread-0 get lock Thread-1 get lock 2
The code is to let the thread in the lock request, wait up to 1 seconds, if more than a second without obtaining a lock to return false, if the lock is obtained to return true, according to the results can be seen Thread-1 thread in 1 seconds to obtain a lock.
We turn on the note//thread.sleep (2000); you will find that Thread-1 or Thread-0 must have an unlocked lock, because the thread that occupies the lock is 2 seconds, and the waiting time for the lock is 1 seconds, so it discards the request lock operation in the instant after 1 seconds.
Java Thread Safety Lock