练习中
Make a program where you have a fashion and a sewing machine, so the Operator enter data width and height, notify the sewing machine in order to perform their job.
Operator
接收数据并处理并通知机器。 Machine
接收数据并完成处理。
但是,当我运行时,Maquina
线程没有收到通知,机器和 Operator
处于无限循环中接收数据。
public class Operator extends Thread {
Scanner in = new Scanner(System.in);
int altura, largura;
public void run() {
while(true) {
synchronized (this) {
System.out.print("Altura: ");
altura = in.nextInt();
System.out.print("Largura: ");
largura = in.nextInt();
notify();
}
}
}
public String getForma() {
return "Forro de mesa : " + (altura * largura);
}
}
public class Maquina extends Thread{
private Operator c;
public Maquina(Operator c) {
this.c = c;
}
public void run() {
while(true) {
synchronized (c) {
try {
System.out.println("Waiting shape...");
c.wait();
System.out.println("init drawn...");
Thread.currentThread().sleep(3000);
System.out.println("drawing...");
Thread.currentThread().sleep(3000);
System.out.println(c.getForma() + ", finalized");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
最佳答案
在运行您的代码时,问题似乎是永远不会到达 "Waiting shape..."
消息。这让我感到惊讶,但似乎 while (true) { synchronized(c)
永远不会让 Maquina
进入 synchronized
block 。
在 Operator.run()
方法的前面添加一个小 sleep 可以解决这个问题。它为 Maquina
获取锁并进入 wait()
提供了时间。
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
synchronized (this) {
System.out.print("Altura: ");
altura = in.nextInt();
System.out.print("Largura: ");
largura = in.nextInt();
notify();
}
}
关于java - 为什么我的线程没有收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17949317/