[英]Enum *seems* to be initialized more than once, the constructor is called more than once. If I’m right, then why?
[英]The problem of this code is in the output. Producer produce more than once. Why and how can I solve it?
这段代码的问题在于输出。 生产者生产不止一次。 为什么以及如何解决? 每个生产者之后应该跟随一个消费者。 这段代码可以粘贴到IDE中直接运行。 我认为问题出在变量就绪上。 我试图在不同的地方移动,但它不起作用。 请帮我。
public class Application
{
public static void main(String[] args) {
Buffer b = new Buffer();
Consumer c1 = new Consumer(b, "C1");
Consumer c2 = new Consumer(b, "C2");
Producer p = new Producer(b);
c1.start();
c2.start();
p.start();
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
p.stop();
c1.stop();
c2.stop();
}
}
class Buffer
{
protected boolean ready = false;
private int num;
public synchronized void put(int x) {
while (ready)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
num = x;
ready = true;
notifyAll();
}
public synchronized int get() {
while (!ready)
{
try
{
wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
ready = false;
notifyAll();
return num;
}
}
class Producer extends Thread
{
private Buffer buffer;
private int h;
public Producer(Buffer b) {
buffer = b;
}
public void run() {
for (int i = 0; i < 10; i++)
{
synchronized (buffer)
{
h = (1 + (int) (Math.random() * 10));
buffer.put(h);
System.out.println("prodotto:" + h);
}
}
}
}
class Consumer extends Thread
{
private Buffer buffer;
private int x;
private String nome;
public Consumer(Buffer b, String s) {
buffer = b;
nome = s;
}
public void run() {
while (true)
{
synchronized (buffer)
{
x = buffer.get();
//C1 C2 prints numbers from 1 to 5
//C2 prints numbers from 6 to 10
if (this.nome == "C1" && x < 6)
{
System.out.println(nome + "- consuma:" + x);
}
if (this.nome == "C2" && x > 5)
{
System.out.println(nome + "- consuma:" + x);
}
}
}
}
}
输出>
produced:9
C2- consumed:9
produced:4
C1- consumed:4
produced:4
produced:9
produced:1
produced:9
C2- consumed:9
produced:10
produced:1
produced:3
但是在每个生产者之后应该跟随一个消费者。 有没有可能帮助我?
问题很简单,虽然我在快速浏览时不明白,但经过 2 或 3 次浏览后,我找到了。 第一个问题是你必须使用equals()
来比较字符串。
您提出的第二个问题是,您仅针对“C2”检查大于 5 的数字,仅针对“C1”检查小于 6 的数字,如果您有大于或等于 6 的“C2”,则不会打印任何内容(如果您小于或等于 5 并且“C1”没有再次打印)(对我来说具有挑战性!!,我认为这是多线程问题)
还有其他错误。 您对消费者使用while(true)
并创建 2 个 cumsumer,它创建未完成的线程(如果需要,将它们设置为 deamon)并且更喜欢在main
方法中使用join
而不是等待。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.