1.生产者消费者模型
技术点:
多线程模型,安全锁机制,等待与唤醒
/**
多线程 生产与消费模型:
分析:
1,创建生产者类继承Thread,只负责生产
2. 创建消费者类继承Thread,只负责消费
3. 两个线程共同操作仓库类Store
4. 加入安全锁及等待与唤醒机制
问题1:生产两个动作,消费也是两个动作,当你打印生产,还没加库存;就已经消费了,库存值不对
处理:加锁 ,解决生产与消费的数据混乱
问题2: 仓满和仓空的限制
处理: 限制仓满,生产者等待(wait);仓空,消费者等待(wait)
细节:
1. 等待时,会将资源交出去
2. 锁对象与等待唤醒的对象是同一个
扩展: 多个生产与多个消费情况
判断中改为while
*/
public class Test1 {
public static void main(String[] args) {
Store store = new Store();
new Producter(store).start();
new Customer(store).start();
//多个生产者和消费者线程
new Producter(store).start();
new Customer(store).start();
}
}
-----生产者-----
public class Producter extends Thread {
private Store store;
public Producter(Store store){ //库存要存进来
this.store = store;
}
@Override
public void run() {
while(true) {
try {
store.push();
} catch (InterruptedException e) {
e.printStackTrace();
} //生产者负责生产
}
}
}
----消费者----
public class Customer extends Thread {
private Store store;
public Customer(Store store) {
this.store = store;
}
@Override
public void run() {
while(true) {
try {
store.pop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //消费者负责消费
}
}
}
---库存---
public class Store {
private int num;
public void push() throws InterruptedException { //库存生产
synchronized (this) {
//生产20件货,就满了,停止生产
while(num>=20) {
this.wait();
}
num++;
System.out.println("生产者已经生产了第"+num+"件货");
this.notify(); //唤醒等待的线程
}
}
public void pop() throws InterruptedException { //库存消费
synchronized (this) { //
while(num<=0) {
this.wait(); //等待消费,等待时,相当于把自身资源交出去了
}
System.out.println("消费者已经消费了第"+num+"件货");
num--;
this.notify(); //唤醒等待的线程
}
}
}
2.线程池
概念:可以认为是线程对象的容器,预先创建多个线程对象,然后根据这些对象可以实现复用
好处:减少创建和销毁线程的数目,提升性能
复用机制: 用完了线程对象后,重新回收到线程池中
class Task implements Runnable{
@Overri