The previous time review colleague's code, found can be simplified into the following model:
Thread 1 |
Thread 2 |
Lock.lock (); Condition.await (); Lock.unlock () |
Lock.lock (); Condition.signal (); Lock.unlock (); |
Suspicion is a deadlock. The following case has been written to simulate a bit, but there is no problem.
But why would T2 enter signal?
According to Javadoc's documentation, this is clearly the third case:
Lock ()
-
Acquires the lock.
Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.
If the current thread already holds the "lock then" the hold count was incremented by one and the method returns immediately.
If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies Dor Mant until the lock has been acquired and at which time the lock hold count is set to one.
It was because T1 entered the await, then the lock on the condition is automatically released, the document is as follows:
await () throws Interruptedexception
Causes the current thread to wait for until it is signalled or interrupted.
The lock associated with the Condition
atomically released and the current thread becomes disabled for thread scheduling p Urposes and lies dormant until one of four things happens:
The code is as follows:
Import Java.util.Date;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;
public class Locktest {
Lock lock = new Reentrantlock ();
Condition finishcondition = Lock.newcondition ();
Class T1 implements Runnable {
public void Run () {
try {
Lock.lock ();
System.out.println ("Enter T1:" + new Date ());
try {
Finishcondition.await ();
System.out.println ("End wating T1:" + new Date ());
} catch (Exception ex) {
Ex.printstacktrace ();
}
} finally {
Lock.unlock ();
System.out.println ("Exit T1:" + new Date ());
}
}
}
Class T2 implements Runnable {
public void Run () {
try {
Lock.lock ();
System.out.println ("Enter T2:" + new Date ());
try {
Thread.Sleep (1000);
Finishcondition.signal ();
} catch (Exception ex) {
Ex.printstacktrace ();
}
} finally {
Lock.unlock ();
System.out.println ("Exit T2:" + new Date ());
}
}
}
public void Run () throws Exception {
New Thread (New T1 ()). Start ();
Thread.Sleep (50);
New Thread (New T2 ()). Start ();
}
public static void Main (string[] args) throws Exception {
Locktest lt = new Locktest ();
Lt.run ();
Thread.Sleep (3000);
SYSTEM.OUT.PRINTLN ("Exit Main.");
}
}
Http://www.cnblogs.com/alphablox/archive/2013/01/13/2858264.html
Sync mechanism lock Beginner (turn)