在这里插入代码片
# Java 线程实现生产者-消费者模式
##思路:实现类似消费者生产者线程之间通讯的功能,每创建一个工人,就让这个工人干活,干一段时间,工人自动消失,然后又去创建一个工人干活;
代码如下:Worker.java
package com.hzl.java.Thread;
public class Worker {
public void doWork() {
try {
System.out.print("编号:" + hashCode() + "工人:正在干活 ");
int wtime = ((int) (Math.random() * 1000));
Thread.sleep(wtime);
System.out.println("工作时长:" + wtime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Factory.java
package com.hzl.java.Thread;
public class Factory {
private static Worker[] box = new Worker[1];
public static void main(String[] args) {
// 创建工人
new Thread(() -> {
while (true) {
synchronized (Object.class) {
try {
if (box[0] != null) {
Object.class.wait();
}
box[0] = new Worker();
Object.class.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
// 获得工人
new Thread(() -> {
while (true) {
synchronized (Object.class) {
try {
if (box[0] == null) {
Object.class.wait();
}
box[0].doWork();
box[0] = null;
Object.class.notify();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
执行结果