import java.util.concurrent.locks.condition;import java.util.concurrent.locks.lock;import java.util.concurrent.locks.reentrantlock;public class lockandunlockdemo { public static void main (String[] args) { &NBSP;&NBSP;CLERK2&NBSP;C=NEW&NBSP;CLERK2 (); thread t=new thread (New producer2 (c)); thread t1=new Thread (New consumer2 (c)); t.start (); t1.start (); }}class clerk2{ Number of producers produced by private int product=0;//to shop assistants private Lock lock = New reentrantlock (); private condition condition_pro = Lock.newcondition (); private condition condition_con = lock.newcondition (); public void addproduct () { lock.lock (); try { if (this.product>5) { try { condition_con.await (); } catch ( Interruptedexception e) { e.printstacktrace (); } }else{ product++; system.out.println (" Production of the "+product+" product "); condition_con.signal (); } }finally { lock.unlock (); } } public void getproduct () { lock.lock (); try { if (this.product<=0) { try { condition_con.await (); } catch (interruptedexception e) { e.printstacktrace (); } } else{   system.out.println ("The consumer buys the first" +product+ "commodity"); product--; condition_pro.signal (); } } finally { lock.unlock (); } } }class producer2 implements runnable{ private clerk2 clerk; public producer2 (Clerk2 clerk) { super (); this.clerk = clerk; }&nBsp; public void run () { System.out.println ("Start of goods production"); while (True) { try { thread.sleep ((int) (Math.random () *10) *1000); } catch (Interruptedexception e) { // TODO Auto-generated catch block e.printstacktrace (); } Clerk.addproduct (); } } }class Consumer2 implements Runnable{ private Clerk2 Clerk; public consumer2 (Clerk2 clerk) { super (); this.clerk = clerk; } public void run () { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Consumers buy goods"); while (true) { try { thread.sleep (( int) (Math.random () *10) *1000); } catch (INTERRUPTEDEXCEPTion e) { // TODO Auto-generated catch block e.printstacktrace (); } Clerk.getproduct (); } } }
This article is from the "Orange Growth Record" blog, be sure to keep this source http://azhome.blog.51cto.com/9306775/1547231
Java uses lock and unlock to implement consumer and producer issues (multithreading)