找了好久不知道代码哪里有问题

来源:5-1 线程间通信

莫非你好棒

2018-01-26 10:46:50

package com.imooc.queue;

public class Consumer implements Runnable{
private Queue q;

public Consumer() {
}
public Consumer(Queue q) {
this.setQ(q); 
}

public Queue getQ() {
return q;
}

public void setQ(Queue q) {
this.q = q;
}

@Override
public void run() {
while(true) {
this.getQ().getN();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


package com.imooc.queue;

public class Producer implements Runnable{
private Queue q;
public Producer() {
}
public Producer(Queue q) {
this.setQ(q); 
}

public Queue getQ() {
return q;
}

public void setQ(Queue q) {
this.q = q;
}

@Override
public void run() {
int i=0;
while(true) {
this.getQ().setN(i++); 
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}



package com.imooc.queue;

public class Queue {
private int n;
boolean flag = false;
public Queue() {
}

public synchronized int getN() {
if(!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费:"+n);
flag = false; //消费完毕,容器中没有数据
notifyAll();
return n;
}

public synchronized void setN(int n) {
if(flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("生产:"+this.getN());
this.n = n;
flag = true; // 生产完毕,容器中已经有数据
notifyAll();
}

}


package com.imooc.queue;

public class Test {

public static void main(String[] args) {
Queue queue = new Queue();
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
}

}


写回答

1回答

irista23

2018-01-26

Queue类中的getN()方法里,System.out.println("生产:"+this.getN());又调用自生this.getN()。改成System.out.println("生产:"+n);

0
hrista23
h 不是递归 看串行了…你把setN()中的输出语句中的getN()改成n就可以了
h018-01-27
共4条回复

0 学习 · 7235 问题

查看课程