生产者与消费者-N:1-基于list
2024-09-11 00:06:13
多个生产者/一个消费者:
/**
* 生产者
*/
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 p1 = new P(stack);
P p2 = new P(stack);
P p3 = new P(stack);
C c1 = new C(stack); P_Thread pThread1 = new P_Thread(p1);
P_Thread pThread2 = new P_Thread(p2);
P_Thread pThread3 = new P_Thread(p3);
C_Thread cThread1 = new C_Thread(c1); pThread1.start();
pThread2.start();
pThread3.start();
cThread1.start();
}
}
运行结果如下:
最新文章
- VMware下对虚拟机Ubuntu14系统所在分区sda1进行磁盘扩容
- Spring学习记录(十四)---JDBC基本操作
- Android 在地图上画矩形
- 《Microsoft SQL Server 2008 Internals》读书笔记
- NABC竞争性需求分析
- Posix线程编程指南(4) 线程终止
- 窥探EasyMock(2)进阶使用篇
- medoo数据库插入的问题
- escape和unescape给字符串编码
- phpmyadmin出现空password登录被禁止
- 编写CodeMirror Modes详解
- Android-Tab
- SSM项目思路整合NEW
- linux关机、重启命令
- LeetCode 905 Sort Array By Parity 解题报告
- [BZOJ 4763]雪辉
- Java基础-hashMap原理剖析
- nyoj 1237 简单dfs
- 为什么java代码中要避免多层深度for循环嵌套
- Kafka技术原理