/**
* 生产者消费者
*/
public class Demo02 {
public static void main(String[] args) {
//创建资源
Resource r = new Resource();
//创建生产者
Producer producer1 = new Producer(r);
Producer producer2 = new Producer(r);
//创建消费者
Consumer consumer1 = new Consumer(r);
Consumer consumer2 = new Consumer(r);
//创建线程
Thread thread1 = new Thread(producer1);
Thread thread2 = new Thread(producer2);
Thread thread3 = new Thread(consumer1);
Thread thread4 = new Thread(consumer2);
//开启线程
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
//资源类
class Resource{
private String name;//资源名称
private int number = 1;//编号
private boolean flag = true;//是否消费
//生产者生产资源
public synchronized void set(String name){
//可以消费,生产停止
while (flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//开始生产
this.name = name+ number;
//编号自增
number++;
//生产完编号自增 以供下次使用
System.out.println(Thread.currentThread().getName()+"正在生产:"+this.name);
//修改标识开始消费
flag = true;
//唤醒所有线程
this.notifyAll();
}
//消费者资源类
public synchronized void get(){
//不能消费
while (!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"正在消费"+this.name);
//修改标识,可以生产。
flag=false;
//唤醒所有线程
this.notifyAll();
}
}
//生产者
class Producer implements Runnable{
private Resource r;
public Producer(Resource r) {
this.r = r;
}
//生产
@Override
public void run() {
while (true){
r.set("面条");
}
}
}
//消费者
class Consumer implements Runnable{
private Resource r;
public Consumer(Resource r) {
this.r = r;
}
@Override
public void run() {
while (true){
r.get();
}
}
}
JAVA 多线程 生产者消费者问题(操作系统实验)
最新推荐文章于 2022-06-15 10:06:35 发布