做一個計劃,使你有一個時尚和一臺縫紉機,所以操作員輸入數據 的寬度和高度,以履行其工作通知縫紉機。
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();
}
}
}
}
}
有什麼問題嗎?你問爲什麼它循環? – Gray
總是在循環中而不是通知線程機器。 從我的理解,應該收到來自用戶的數據,並在我收到數據時傳遞給機器 – diegohsi