java 生产者消费者问题-多线程与死锁
来源:互联网 发布:淘宝降价通知 编辑:程序博客网 时间:2024/05/29 18:37
代码直接示例。
//想象这是馒头,每个馒头有自己的id
class Item{
private int id=0;public Item(int id) {
this.id=id;
}
public int getID(){
return id+1;
}
}
//想象这是装馒头的框子
class Stack{
//最多装5个的数组
Item []arr=new Item[5];int index=0; //记录装了几个
//添加与移除方法:都得上锁,不然乱了。关于这个问题点击打开链接,这里有一个例子找看看
public synchronized void add(Item it){while(index==5){
try {
wait(); //如果满了就不能装了,线程wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
arr[index]=it;
index++;
notify(); //别忘了唤醒移除线程
}
while(index==0){
try {
this.wait(); 没了就不能去除了,wait
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
Item it=arr[index];
arr[index]=null;
return it;
}}
生产馒头的:生产者
class Produce implements Runnable{
Stack s=null;
public Produce(Stack s){
this.s=s;
}
//生产20个就算了吧,不然循环起来没完了
public void run(){for(int i=0;i<20;i++){
s.add(new Item(i));
System.out.println("Pro: "+(i+1));
try {
Thread.sleep(400); 睡一会是为了更好的观察输出,你设成0的话 再看就看不出来运行过程了
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
消费者
class Consume implements Runnable{Stack s=null;
public Consume(Stack s){
this.s=s;
}
public void run(){
for(int i=0;i<20;i++){
System.out.println("Remove: "+ s.remove().getID());
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TestPandC{
public static void main(String[] args){
Stack s=new Stack();
new Thread(new Produce(s)).start();
new Thread(new Consume(s)).start();
}
}
运行一下看看吧
0 0
- java 生产者消费者问题-多线程与死锁
- java多线程(同步与死锁问题,生产者与消费者问题)
- Java 多线程编程(生产者和消费者问题以及死锁)
- JAVA多线程实例(生产者与消费者问题)
- java多线程同步:生产者与消费者问题
- Java多线程--生产者与消费者问题
- Java经典多线程问题--生产者与消费者
- 多线程-生产者与消费者问题
- java多线程 生产者消费者问题
- java多线程 生产者 消费者 问题 。。。
- Java 多线程:生产者消费者问题
- Java多线程生产者消费者问题
- java多线程 生产者与消费者
- 【Java多线程】-生产者与消费者
- JAVA - 多线程 - 生产者与消费者
- Java多线程-生产者与消费者
- 死锁,生产者与消费者
- java多线程之生产者与消费者问题的简单模拟
- C语言中栈帧的创建与销毁
- sqoop-导入数据出现java.sql.SQLException: Streaming result set com.mysql.jdbc.
- Django Ubuntu部署: python3 + mysql + nginx + uswgi
- web安全之xss
- 编写基于stm32f407-uclinux下的led灯驱动
- java 生产者消费者问题-多线程与死锁
- Yii2 RABC
- windows CMD 命令总结
- 大家好,我是小白请多多关照
- 热更新Tinker研究(五):Application的隔离
- 奇迹一小点——js前端学习笔记
- duilib richedit 添加文本提示
- Java-IO 文件操作
- 【原创】PHP 表格 分页 显示