应用番茄酱线程没有唤醒,我不知道为什么!
我正在学习Java线程交互。
我确实使用了notifyAll()方法,但是"applyKetchup“线程不能按时唤醒!
线程应该有足够的时间来唤醒,这是难以置信的。
预期结果为
makeBread!applyKetchup!makeBread!applyKetchup!makeBread!applyKetchup!makeBread!applyKetchup!makeBread!applyKetchup!实际结果是
makeBread!applyKetchup!makeBread!makeBread!makeBread!makeBread!applyKetchup!applyKetchup!applyKetchup!applyKetchup!这是我的代码。
import java.util.ArrayList;
public class ProduceHamburgers {
public static void main(String[] args) {
HamburgerFactory hamburgerFactory = new HamburgerFactory();
hamburgerFactory.delivery(5);
}
}
class HamburgerFactory {
private ArrayList<Hamburger> hamburgers = new ArrayList<>();
private ArrayList<Hamburger> breads = new ArrayList<>();
public void delivery(int amount) {
for (int index = 0; index < amount; index++) {
new Thread(() -> applyKetchup(), "applyKetchup-" + index).start();
}
for (int index = 0; index < amount; index++) {
new Thread(() -> makeBread(), "makeBread-" + index).start();
}
}
private synchronized void applyKetchup() {
while (breads.isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Hamburger current = breads.get(0);
breads.remove(current);
current.hadKetchup = true;
System.out.print("applyKetchup!");
hamburgers.add(current);
}
private synchronized void makeBread() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
breads.add(new Hamburger());
System.out.print("makeBread!");
this.notifyAll();
}
}
class Hamburger {
public boolean hadKetchup = false;
}提前感谢!
发布于 2019-11-06 18:13:42
import java.util.ArrayList;
public class ProduceHamburgers {
public static void main(String[] args) {
HamburgerFactory hamburgerFactory = new HamburgerFactory();
hamburgerFactory.delivery(5);
}
}
class HamburgerFactory {
private ArrayList<Hamburger> hamburgers = new ArrayList<>();
private ArrayList<Hamburger> breads = new ArrayList<>();
public void delivery(int amount) {
for (int index = 0; index < amount; index++) {
new Thread(() -> applyKetchup(), "applyKetchup-" + index).start();
}
for (int index = 0; index < amount; index++) {
new Thread(() -> makeBread(), "makeBread-" + index).start();
}
}
private synchronized void applyKetchup() {
while (breads.isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Hamburger current = breads.get(0);
breads.remove(current);
current.hadKetchup = true;
System.out.print("applyKetchup!");
hamburgers.add(current);
this.notifyAll();
}
private synchronized void makeBread() {
while (!breads.isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
breads.add(new Hamburger());
System.out.print("makeBread!");
this.notifyAll();
}
}
class Hamburger {
public boolean hadKetchup = false;
}O/P makeBread!applyKetchup!makeBread!applyKetchup!makeBread!applyKetchup!makeBread!applyKetchup!makeBread!applyKetchup!
https://stackoverflow.com/questions/58727235
复制相似问题