我想打電話給我通知我的線程來自另一個班級,但我認爲我會全力以赴。我已經閱讀了許多人嘗試類似的事情的例子,但我似乎無法將其應用於我的代碼。我認爲我的問題是我的同步對象,但我不確定。林新線程,所以不要羞辱我。下面是我的代碼示例:)如何通知另一個班級的線程
public class SendTextOffEdt implements Runnable {
private static final long SLEEP_TIME = 3000;
public static String TEXT = "Sent off of EDT\n";
private TextBox myTextBox;
//public boolean waitBoolean = false;
public SendTextOffEdt(TextBox myTextBox) {
this.myTextBox = myTextBox;
}
@Override
public void run() {
synchronized(this){
//while (true) {
try {
myTextBox.appendTextOffEdt(TEXT);
wait();
} catch (InterruptedException e) { //******** i changed this from another exception!!
System.out.println("*----------thread interrupted!");
myTextBox.appendTextOffEdt(TEXT);
}
}
}
}
public class Combat extends JPanel {
private SendTextOffEdt sendTextOffEdt = new SendTextOffEdt(textbox); //just added this object
public Combat(){
TestNotify();
}
public void TestNotify(){
synchronized(sendTextOffEdt){ //added the sendTextOffEdt object here
sendTextOffEdt.notifyAll();
System.out.println("has been notified");
}
}
}
我編輯了我的代碼來完成你的建議。讓我知道這是否有效。我將sendtextoffedt對象添加到戰鬥類並引用它。如果我告訴你,我可能只是簡單地在線程通知時打印一個字符串。這有幫助嗎? –
@CameronRoberson您的wait()調用後沒有任何代碼。當SendTextOffEdt醒來時,它什麼也不做。 – Jay
我在我的程序中添加了代碼(不是這裏的代碼),它仍然沒有做任何事情。它可能與eventdispatch線程有關。戰鬥類是從一個行動事件中調用的,我相信這意味着它在EDT上是正確的?我需要有一個try catch語句來檢查這個嗎?讓我知道。謝謝傑伊, –