gpt4 book ai didi

java - JUnit 测试后多线程应用程序将无法运行

转载 作者:行者123 更新时间:2023-12-02 11:31:19 26 4
gpt4 key购买 nike

我的打印机柜台学校问题遇到了问题。它应该是一个多线程应用程序并且到目前为止运行良好。但是当我第二次或第三次运行它时,它就不再工作了..没有错误消息。看起来线程永远 hibernate 左右。另外,当我使用 JUnit 测试对其进行测试时,它不会工作。但有时确实如此......这本身就很奇怪。

public class CounterPrinter {


public static void main(String[] args) throws InterruptedException {
if (args.length != 2) {
System.out.println("Usage: CounterPrinter <min> <max>");
System.exit(1);
}
Storage s = new Storage();
Printer d = new Printer(s, Integer.parseInt(args[1]));
Counter z = new Counter(s, Integer.parseInt(args[0]), Integer.parseInt(args[1]));

z.start();
d.start();

z.join();
d.join();


Thread.sleep(5000);

}

}



public class Printerextends Thread {
private Storage storage;
private Integer ende;


Printer(Storage s, Integer ende) {
this.storage = s;
this.ende = ende;
}


@Override
public void run() {
while (storage.hasValue()) {
try {

System.out.print(speicher.getValue(ende) + " ");
Thread.sleep(50);

} catch (InterruptedException e) {
e.printStackTrace();
}
}


}

}

public class Counter extends Thread {
private Storage speicher;
private int max, min;

Counter(Storages, int min, int max) {
this.storage = s;
this.max = max;
this.min = min;
}


@Override
public void run() {
for (int i = min; i <= max; i++) {
try {
storage.setValue(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}


public class Storage implements StorageIf {
private Integer wert;
private boolean hasValue = false;

@Override
public synchronized Integer getValue(Integer ende) throws InterruptedException {
if(wert.equals(ende)){
hasValue = false;
return wert;
}else {
while (!hasValue()) {
wait();
}

hasValue = false;
notifyAll();
return wert;
}
}


@Override
public synchronized void setValue(Integer wert) throws InterruptedException {
while (hasValue()){
wait();
}
hasValue = true;
this.wert = wert;
notifyAll();

}


@Override
public boolean hasValue() {
return hasValue;
}
}

希望有人能发现我犯的错误

非常感谢!

最佳答案

问题是你混淆了两种状态:

  • 当前有可用值
  • 不会再有任何值

向 Storage 类添加一个 hasEnded() 方法,检查是否已达到最终值。确保同步此方法以及 hasValue() 方法。读写访问都需要同步!

然后使Printer的while循环检查hasEnded,而不是hasValue

最后:摆脱所有 sleep() 调用。

你自己的答案,用 sleep 来解决问题,并不是真正的解决方案。线程安全程序的正常运行并不依赖于计算机的性能。

关于java - JUnit 测试后多线程应用程序将无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com