Java5 has added a lot of thread synchronization features, such as explicit lock, read-write lock readwritelock, conditional variable condition, etc., although these features can be implemented using the previous synchronized synchronization keyword, but their use of synchronization keyword not only manages chaos , and error prone. The following is a better solution to the problem of producer consumers by using explicit lock and conditional variable condition, and it is well understood that the readers of lock and condition can consult the relevant instructions themselves.
Consumer.java
Package Creatorandconsumer;
public class Consumer implements Runnable {
/**
* Thread Resource * *
private Plate Plate;
Public Consumer (Plate Plate) {
this.plate = Plate;
}
@Override public
Void Run () {
Plate.getegg ();
}
}
Creator.java
Package Creatorandconsumer;
/** *
producer
* * @author Martin/Public
class Creator implements Runnable {
/**
* Thread Resource
* /
private Plate Plate;
Public Creator (Plate Plate) {
this.plate = Plate;
}
@Override public
Void Run () {
Object egg = new Object ();
Plate.addegg (egg);
}
Plate.java
Package Creatorandconsumer;
Import java.util.List;
Import java.util.concurrent.locks.*; /** * plate, indicating shared resources * * @author Martin/public class Plate {private list<object> eggs = new Arraylist<obj
Ect> ();
/** * Lock */private lock lock;
/** * is greater than 0 pieces of variable, used to ensure that the consumption of resources can be consumed * * Private Condition more0condition;
Public Plate () {lock = new reentrantlock ();
More0condition = Lock.newcondition ();
/** * Get Egg * * @return/public Object Getegg () {lock.lock ();
try {while (Eggs.size () < 1) {more0condition.await ();
SYSTEM.OUT.PRINTLN ("Consumers take eggs, current remaining:" + eggs.size ());
Object egg = eggs.get (0);
Eggs.remove (0);
return egg;
catch (Interruptedexception e) {e.printstacktrace ();
finally {Lock.unlock ();
return null;
}
/*** Add Egg * * @return/public void Addegg (Object egg) {lock.lock ();
System.out.println ("producer eggs, current remaining:" + eggs.size ());
Eggs.add (egg);
More0condition.signalall ();
Lock.unlock ();
}
}
Tester.java
Package Creatorandconsumer;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
public class Tester {public
static void Main (string[] args)
{
//shared resource
Plate Plate = new Plate ();
Executorservice pool = executors.newfixedthreadpool (MB);
Add producer and consumer for
(int i = 0; i < 1000 i + +)
{
Pool.execute (new Creator (plate));
Pool.execute (new Consumer (plate));
}
Pool.shutdown ();
}
</pre><pre>