Java 实现生产者消费者问题
废话不多说直接上代码
package test;
//资源
class Resources{
private boolean flag = true; //互斥锁,即只能被生产者或者消费者中的一种来消费资源
//flag == True 允许生产
//flag == False 允许消费
private int x=0; //资源数量
//******生成资源******* synchronized为只允许一个进程访问
public synchronized void set() {
if (!this.flag) { //如果不允许生产
try {
super.wait(); //等待,父类为Object 方法为wait(); super调用父类方法
}catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果 flag为true 允许生产
try {//模拟生产时间
Thread.sleep(100); //线程等待100ms
}catch (InterruptedException e) {
e.printStackTrace();
}
this.x++; //生成资源,资源+1
this.flag = false ;//生产过后,禁止在进行生产
super.notify();//如果此时有等待的线程,唤醒等待的线程。
}
//******消费资源*******
public synchronized void get() {
//如果不允许消费
if (this.flag) {
try {
//等待
super.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
//允许消费
try {
//模拟消费时间
Thread.sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
//消费后 资源-1
this.x--;
//禁止再次消费
this.flag = true ;
super.notify();//如果此时有等待的线程,唤醒等待的线程。
}
//显示资源的数目
public int showX() {
return this.x;
}
}
//定义生产者类
class Producer implements Runnable{//继承接口Runnable
//
private Resources res = null;
//初始化
public Producer(Resources res) {
this.res = res ;
}
//复写run函数
public void run() {
for(int i=0; i<10; i++) {
this.res.set();
System.out.println("生产者生产了: "+this.res.showX()+" 个资源");
}
}
}
//定义消费者类
class Consumer implements Runnable{
private Resources res = null;
//初始化
public Consumer(Resources res) {
this.res = res ;
}
//复写run函数在这里插入代码片
public void run() {
for(int i=0; i<10; i++) {
this.res.get();
System.out.println("消费者消费后还剩: "+this.res.showX()+ "个资源");
}
}
}
public class Pro_and_Con {
public static void main(String args[]) throws Exception {
Resources res = new Resources() ;
new Thread(new Consumer(res)).start();
new Thread(new Producer(res)).start();
}
}