package cn.wzy.Lock;
import java.util.Random;
public class ConsumerAndProducer {
static String[] food = new String[5];
static String take() throws InterruptedException {
synchronized (food) {
while (true) {
for (int i = 0; i < 5; i++) {
if (food[i] != null) {
String tmp = food[0];
food[0] = null;
food.notifyAll();
System.out.println(Thread.currentThread().getId() + \" 获得了 \" + i + \" 的数据\");
return tmp;
}
}
food.wait();
}
}
}
static void put(String data) throws InterruptedException {
synchronized (food) {
while (true) {
for (int i = 0; i < 5; i++) {
if (food[i] == null) {
food[i] = data;
food.notifyAll();
System.out.println(Thread.currentThread().getId() + \" 生产了 \" + i + \" 的数据\");
return;
}
}
food.wait();
}
}
}
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 10; i++) {
if (i % 2 == 1) {
new Thread(()->{
try {
Thread.sleep(1000);
take();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.interrupted();
}
}).start();
} else {
new Thread(()->{
try {
put(random.nextLong() + \"\");
} catch (InterruptedException e) {
e.printStackTrace();
Thread.interrupted();
}
}).start();
}
}
}
}
继续阅读与本文标签相同的文章
上一篇 :
华为:已完成多个SA预商用网络建设
下一篇 :
新360行之共享单车运维员:守护城市单车秩序
-
阿里云开发者社区问答栏目提问规范
2026-05-18栏目: 教程
-
小伙上演“无人驾驶”手舞足蹈,女网友拍视频发朋友圈结果“悲剧了”……
2026-05-18栏目: 教程
-
迎来“无后门协议”!持续压制无效?5G建设选择在于技术问题
2026-05-18栏目: 教程
-
Pepper Metrics - Spring/Spring Boot应用性能监控利器
2026-05-18栏目: 教程
-
ZKEYS:数字化时代,IDC云化解决方案的探索实践
2026-05-18栏目: 教程
