1.生产者消费者在处理并发时是很常用的处理方式 是很有必要掌握的。
2.Lock其实就相当于传统的synchronize Condition的await()相当于wait() signal()相当于notify().
3.没有使用传统的 wait() 和notify()的原因是 Condition可以有多个,能够用来解决更加复杂的情况.
直接上代码:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConsumerAndProducter {
public static void main(String[] args) {
new ConsumerAndProducter().work();
}
int length = 8;// 仓库最大容量
Lock lock = new ReentrantLock();
Condition notFull = lock.newCondition();
Condition notEmpty = lock.newCondition();
List<Productor> Productors = new ArrayList<>();
private void work() {
new Thread(new Runnable() {
public void run() {
consume();
}
}).start();
new Thread(new Runnable() {
public void run() {
consume();
}
}).start();
new Thread(new Runnable() {
public void run() {
product();
}
}).start();
}
/**
* 消费
*/
private void consume() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
lock.lock();
try {
while (Productors.size() == 0) {
System.out.println("容器为空 等待生产"+Thread.currentThread().getName());
notEmpty.await();
}
Productors.remove(0);
System.out.println("消费了一个产品"+Thread.currentThread().getName());
System.out.println("容器有空余 通知生产"+Thread.currentThread().getName());
notFull.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
/**
* 生产
*/
private void product() {
while(true){
try {
Thread.sleep(500); //生产效率
} catch (InterruptedException e1) {
e1.printStackTrace();
}
lock.lock();
try {
while (Productors.size() == 8) {
System.out.println("容器已满 等待消费"+Thread.currentThread().getName());
notFull.await();
}
Productors.add(new Productor()); //生产机器数
System.out.println("产品已生产 通知可以消费"+Thread.currentThread().getName());
notEmpty.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
/**
* 产品
* @author z2wenfa
*
*/
private class Productor {
public Productor() {
}
}
}