生产者与消费者-1:N-基于list
2024-08-24 15:00:42
一个生产者/多个消费者:
/**
* 生产者
*/
public class P { private MyStack stack; public P(MyStack stack) {
this.stack = stack;
} public void pushService() {
stack.push();
}
}
/**
* 消费者
*/
public class C { private MyStack stack; public C(MyStack stack) {
this.stack = stack;
} public void popService() {
System.out.println("pop = " + stack.pop());
}
}
/**
* 模拟栈
*/
public class MyStack { private List<Object> list = new ArrayList<>(); public synchronized void push() {
try {
while(list.size() == 1) {
this.wait();
}
list.add(""+Math.random());
this.notifyAll();
System.out.println("push:" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
} public synchronized String pop() {
String value = "";
try {
while(list.size() == 0) {
System.out.println("pop 操作中:" + Thread.currentThread().getName() + "wait状态");
this.wait();
}
value = ""+list.get(0);
list.remove(0);
this.notifyAll();
System.out.println("pop:" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}
/**
* 生产者线程
*/
public class P_Thread extends Thread { private P p; public P_Thread(P p) {
this.p = p;
} @Override
public void run() {
while (true) {
p.pushService();
}
}
}
/**
* 消费者线程
*/
public class C_Thread extends Thread { private C c; public C_Thread(C c) {
this.c = c;
} @Override
public void run() {
while (true) {
c.popService();
}
}
}
/**
* 测试类
*/
public class Run { public static void main(String[] args) {
MyStack stack = new MyStack();
//一个生产者
P p = new P(stack);
//多个消费者
C c1 = new C(stack);
C c2 = new C(stack);
C c3 = new C(stack); //一个生产者线程
P_Thread pThread = new P_Thread(p);
//多个消费者线程
C_Thread cThread1 = new C_Thread(c1);
C_Thread cThread2 = new C_Thread(c2);
C_Thread cThread3 = new C_Thread(c3); //启动
pThread.start();
cThread1.start();
cThread2.start();
cThread3.start();
}
}
运行结果如下:
最新文章
- C# SaveFileDialog的用法(转载)
- KindEditor4.1.10,支持粘贴图片(转载!)
- C#中子类与父类的相互转换
- OpenMp之sections用法
- [itint5]支持删除的后继查询
- 06_init()和destroy()方法
- IOS开发中摇一摇是怎么实现的
- k8s容器的资源限制
- PHP+ajax实现二级联动
- 给 Linux 系统“减肥”,系统垃圾清理_系统安装与配置管理_Linux Today - Google Chrome
- Android 第三课 构建简单的用户界面
- jQuery-contextMenu使用教程
- Talend 从Excel导入Saleforce数据(二) TMAP是精髓
- android开发(36) Android WebView背景设置为透明
- 【android】模拟点击某个指定坐标作用在View上
- 禅道ZenTao在windows和Lniux下集成安装环境和一键安装方法整理
- jqGrid 将行的字变成超连接
- jQuery获取input复选框的值
- html和java的交互,利用jsBridge开源框架
- 生成二维码 加密解密类 TABLE转换成实体、TABLE转换成实体集合(可转换成对象和值类型) COOKIE帮助类 数据类型转换 截取字符串 根据IP获取地点 生成随机字符 UNIX时间转换为DATETIME\DATETIME转换为UNIXTIME 是否包含中文 生成秘钥方式之一 计算某一年 某一周 的起始时间和结束时间