The lock writing method of the producer-consumer case
Which involves the usage of Condition, a brief introduction:
The 1.Condition interface describes condition variables that may be related to locks. These variables are similar in usage to implicit monitors accessed using Object.wait, but provide more powerful functionality. What needs to be special is that a single lock may be associated with multiple Condition objects. To avoid compatibility problems, the names of the Condition methods are different from those in the corresponding Object version.
2. In the Condition object, the methods corresponding to wait, notify, notifyAll are await, signal, signalAll respectively
3. The Condition instance is essentially bound to a lock. To get a Condition for a specific Lock instance, use the newCondition() method.
Specific code:
public class TestProductorAndCustomerForLock { public static void main(String[] args){ Clerk clerk = new Clerk(); Producer producer = new Producer(clerk); Customer customer = new Customer(clerk); new Thread(productor,"productor A").start(); new Thread(productor,"productor B").start(); new Thread(customer,"customer A").start(); new Thread(customer,"customer B").start(); } } class Clerk { private int productor = 0; private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); // stock public void get() { lock.lock(); try { while (productor >= 1) { System.out.println("Product is full!"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace (); } } System.out.println(Thread.currentThread().getName() + ":" + ++productor); condition.signalAll(); }finally { lock.unlock(); } } // sell public void sale() { lock.lock(); try { while (productor <= 0) { System.out.println("Out of stock!"); try { condition.await(); } catch (InterruptedException e) { e.printStackTrace (); } } System.out.println(Thread.currentThread().getName() + ":" + --productor); condition.signalAll(); }finally { lock.unlock(); } } } class Productor implements Runnable{ private Clerk clerk; public Productor(Clerk clerk) { this.clerk = clerk; } @Override public void run() { for (int i = 0; i < 20; i++) { try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace (); } clerk.get(); } } } class Customer implements Runnable{ private Clerk clerk; public Customer(Clerk clerk) { this.clerk = clerk; } @Override public void run() { for (int i = 0; i <20 ; i++) { clerk.sale(); } } }operation result: