英文:
Java: ProducerConsumer
问题
我在代码中没有看到问题,但结果未在 Eclipse 的控制台窗口中显示。
有什么问题吗?
class Buffer{
private int data;
private boolean empty = true;
public synchronized int get() {
while(empty) {
try {
wait();
} catch (InterruptedException e) {
}
}
empty = true;
notifyAll();
return data;
}
public synchronized void put(int data) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
}
}
empty = false;
this.data = data;
notifyAll();
}
}
class Producer implements Runnable{
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
for (int i=0; i<0; i++) {
buffer.put(i);
System.out.println("Producer: " + i + "th cake produced.");
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
class Consumer implements Runnable{
private Buffer buffer;
public Consumer(Buffer drop) {
this.buffer = drop;
}
public void run() {
for(int i=0; i<10; i++) {
int data = buffer.get();
System.out.println("Consumer: " + data + "th cake consumed.");
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Buffer buffer = new Buffer();
(new Thread(new Producer(buffer))).start();
(new Thread(new Consumer(buffer))).start();
}
}
英文:
I don't see any problem with this code, but the result doesn't display in the console window in eclipse.
What's the problem?
class Buffer{
private int data;
private boolean empty = true;
public synchronized int get() {
while(empty) {
try {
wait();
} catch (InterruptedException e) {
}
}
empty = true;
notifyAll();
return data;
}
public synchronized void put(int data) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
}
}
empty = false;
this.data = data;
notifyAll();
}
}
class Producer implements Runnable{
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
public void run() {
for (int i=0; i<0; i++) {
buffer.put(i);
System.out.println("Producer: " + i + "th cake produced.");
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
class Consumer implements Runnable{
private Buffer buffer;
public Consumer(Buffer drop) {
this.buffer = drop;
}
public void run() {
for(int i=0; i<10; i++) {
int data = buffer.get();
System.out.println("Consumer: " + data + "th cake comsumed.");
try {
Thread.sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
public class ProducerConsumerTest {
public static void main(String[] args) {
Buffer buffer = new Buffer();
(new Thread(new Producer(buffer))).start();
(new Thread(new Consumer(buffer))).start();
}
}
答案1
得分: 1
在生产者的run()方法中,您有一个错误的for循环:
for (int i=0; i<0; i++)
但它应该是:
for (int i=0; i<10; i++)
那可能是一个打字错误
英文:
In the run() method of the producer you have bad for loop
for (int i=0; i<0; i++)
but it should be
for (int i=0; i<10; i++)
That was probably a typo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论