Synchronized synchronizing code blocks:
Package Net.flyingfat.lock;public class SyncLock {public static void main (String args[]) {final SyncLock lock=new SyncLock (); Thread.CurrentThread (). SetName ("main"); new Thread (New Runnable () {public void run () {Thread.CurrentThread (). SetName ( "Sub"); try {thread.sleep (+); lock.run2 ();} catch (Exception e) {e.printstacktrace ();}}). Start (); Lock.run2 ();} Public synchronized void Run2 () {try{system.out.println ("thread" +thread.currentthread (). GetName () + ": Get Object Lock" if (Thread.CurrentThread (). GetName (). Equals ("main")) {System.out.println ("main Thread block, Release object lock"); This.wait (); The main thread executes until this is blocked, and the object lock is freed, allowing the sub thread to enter the method System.out.println ("Main thread is Notifyed,get object lock again");} else if (Thread.CurrentThread (). GetName () Equals ("sub")) {this.notify ();//sub thread gets the object lock released by the main thread, Wakes up the blocked main thread so that it executes System.out.println ("Sub thread Notify");} System.out.println (Thread.CurrentThread (). GetName () + ": Execute Over,release Object lock"); catch (Exception e) {e.printstacktrace ();}}}
Reentrantlock Synchronous Code implementation:
Package Net.flyingfat.lock;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.reentrantlock;public class Reenlock {reentrantlock lock=new ReentrantLock (); Condition condition=lock.newcondition ();p ublic static void Main (string[] args) {thread.currentthread (). SetName ("Main "); final Reenlock test4=new Reenlock (); New Thread (New Runnable () {public void run () {try {thread.sleep (); Test4.run () ;} catch (Interruptedexception e) {e.printstacktrace ();}}}, "Sub"). Start (); Test4.run ();} public void Run () {try{lock.lock (); System.out.println ("Thread:" +thread.currentthread (). GetName () + "get Lock"), if (Thread.CurrentThread (). GetName (). Equals ("main")) {System.out.println ("Main thread block, release object lock"); condition.await ();//main thread executes until it blocks, And frees the object lock, allowing the sub thread to enter the method System.out.println ("Main thread is Signaled,get object lock again");} if (Thread.CurrentThread (). GetName () Equals ("sub")) {condition.signal ();//sub thread gets the object lock released by the main thread, Wakes up the blocked main thread and makes it perform System.out.println ("Sub thread sigNal ");}} catch (Exception e) {e.printstacktrace ();} Finally{lock.unlock (); System.out.println ("Thread:" +thread.currentthread (). GetName () + "release lock");}} }
Synchronized and Reentrantlock synchronization code block simple implementation