我写了一个java的生产消费问题,代码如下,但是出来的结果消费的情况总是不对,哪位大神可以帮忙解决一下 5
packagetestThread;publicclassProduceConsumes{publicstaticvoidmain(String[]args){SynSt...
package testThread;
public class ProduceConsumes {
public static void main(String[] args) {
SynStack stack = new SynStack();
Produce produce = new Produce(stack);
Consume consumer = new Consume(stack);
new Thread(produce).start();
new Thread(consumer).start();
}
}
class Point{
int id ;
Point(int id){
this.id = id;
}
@Override
public String toString() {
return "Point "+id;
}
}
class SynStack{
int index=0;
Point[] pt = new Point[5];
public synchronized void push(Point point) {
while (index==pt.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
pt[index] = point;
index ++;
}
public synchronized Point pop() {
while (index==0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index --;
return pt[index];
}
}
class Produce implements Runnable{
SynStack ss = null;
public Produce (SynStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Point p = new Point(i);
ss.push(p);
System.out.println(" 生产了第"+p);
}
}
}
class Consume implements Runnable{
SynStack ss = null;
public Consume (SynStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
ss.pop();
System.out.println("消费了第"+ss.pop());
}
}
}
结果是: 展开
public class ProduceConsumes {
public static void main(String[] args) {
SynStack stack = new SynStack();
Produce produce = new Produce(stack);
Consume consumer = new Consume(stack);
new Thread(produce).start();
new Thread(consumer).start();
}
}
class Point{
int id ;
Point(int id){
this.id = id;
}
@Override
public String toString() {
return "Point "+id;
}
}
class SynStack{
int index=0;
Point[] pt = new Point[5];
public synchronized void push(Point point) {
while (index==pt.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
pt[index] = point;
index ++;
}
public synchronized Point pop() {
while (index==0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index --;
return pt[index];
}
}
class Produce implements Runnable{
SynStack ss = null;
public Produce (SynStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Point p = new Point(i);
ss.push(p);
System.out.println(" 生产了第"+p);
}
}
}
class Consume implements Runnable{
SynStack ss = null;
public Consume (SynStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
ss.pop();
System.out.println("消费了第"+ss.pop());
}
}
}
结果是: 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询