我的代碼有問題。
我的任務是 wrtie 程式,它類似于一些生產煎餅的工廠,我必須使用同步佇列。
共有三個步驟:
1. 油炸。
之后在另一個執行緒中:
2. 潤滑。
最后一個是:
3. 把這個煎餅卷起來:)
在我的程式中,我開始煎炸并創建“put”,這意味著我正在等待另一種方法中的“take”呼叫。但它不起作用。當程式想要呼叫 Greasing 類中的“greasing”方法時它會停止。
主要的:
public static void main(String[] args) {
Factory f1 = new Factory();
f1.start();
Greasing g1 = new Greasing(f1);
g1.start();
RollingUp r1 = new RollingUp(f1);
r1.start();
}
工廠等級:
public class Factory extends Thread{
// 0 - frying
// 1 - greasing
// 2 - rolling up
SynchronousQueue<String> list = new SynchronousQueue<>();
@Override
public void run() {
try{
while(true) frying();
}catch(InterruptedException e){
e.printStackTrace();
}
}
private synchronized void frying()throws InterruptedException{
System.out.println("I'm frying now");
list.put("Frying");
notify();
}
public synchronized void greasing() throws InterruptedException{
notify();
list.take();
System.out.println("I'm greasing now");
list.put("Greasing");
}
public synchronized void rollingup()throws InterruptedException{
notify();
list.take();
System.out.println("I'm rolling up now");
list.put("Rolling up");
}
}
潤滑等級:
public class Greasing extends Thread{
Factory f1;
public Greasing(Factory f1) {
this.f1 = f1;
}
@Override
public void run() {
try{
while(true){
f1.greasing();
sleep(1000);
}
}catch(Exception e){
e.getMessage();
}
}
}
上卷類:
public class RollingUp extends Thread{
Factory f1;
RollingUp(Factory f1){
this.f1 = f1;
}
@Override
public void run() {
try{
while(true){
f1.rollingup();
sleep(1000);
}
}catch(Exception e){
e.getMessage();
}
}
}
uj5u.com熱心網友回復:
你有兩種問題:
從您的代碼中洗掉
notify()ansychronized,這會阻止您,因為它synchronized在 Factory 類上放置了一個鎖,因此 2 個執行緒無法同時進入 Factory 同步方法。最好在正確的類中移動代碼,Greasing 必須發生在 Greasing 類中。這將幫助您整理秩序并像物件一樣思考。修復了 1. 您將看到每個操作現在都在進行,直到所有執行緒都在
put. 這是因為您需要為每個“消費者”設定不同的佇列。在您的代碼中,您可以從油炸中觸發 Rollingup,因為串列中的物件之間沒有區別。
Frying 操作必須將物件放入 grassing 佇列,Greasing 操作必須從他的佇列中消費,然后將物件放入 Rollingup 佇列
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/403032.html
標籤:
上一篇:創建執行緒花費的時間太長
下一篇:存盤執行緒的函式輸入
