多线程之线程高级

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值