java实现生产者消费者问题 在下面的注释处补充代码 急用
发布网友
发布时间:2022-04-30 03:35
我来回答
共3个回答
热心网友
时间:2023-10-09 20:32
我这里有个消费者问题能跑的,你可以参考下(其中两处Math.random() * 200多修改几次这里的值看效果跟好):
public class ProcerConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Procer p = new Procer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
class WoTou {
int id;
WoTou(int id) {
this.id = id;
}
}
class SyncStack {
int index = 0;
WoTou[] arrWT = new WoTou[6];
public synchronized void push(WoTou wt) {
while(index == arrWT.length) {
try {
System.out.println("生产者说篓子满了,我去休息");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
arrWT[index] = wt;
index++;
System.out.println("生产前后" + index +"个");
}
public synchronized WoTou pop() {
while(index ==0) {
try {
System.out.println("消费者说篓子空了,我去休息");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
System.out.println("消费后剩余" + index +"个");
return arrWT[index];
}
}
class Procer implements Runnable {
SyncStack ss = null;
Procer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++){
WoTou wt = new WoTou(i);
ss.push(wt);
try {
Thread.sleep((int)(Math.random() * 200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
WoTou wt = ss.pop();
try {
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
热心网友
时间:2023-10-09 20:33
@SuppressWarnings("unchecked")
public void put(Object proct) {
synchronized(internalBuffer) {
if(internalBuffer.size() >= bufCount) {
wait();
}
notify();
System.out.println("Procer put: " + proct + " " + this);
}
}
public Object get() {
synchronized(internalBuffer) {
Object proct = null;
if(internalBuffer.isEmpty()) {
wait();
}
notify();
System.out.println("Consumer got: " + proct + " " + this);
return proct;
}
}
应该就是这样了,不知道是不是满足你的要求
热心网友
时间:2023-10-09 20:33
一楼的真可耻
另外,虚机团上产品团购,超级便宜