I have a method that uses a SwingWorker. Part of the code is shown below:
public class mySocket {
public void writePacket(final String packet) {
// schedules execution on the single thread of the executor (so only one
// background operation can happen at once)
//
executor.execute(new SwingWorker<String, Void>() {
@Override
protected String doInBackground() throws Exception {
// called on a background thread
System.out.println("writing out this packet->" + packet + "
<-");
out.println(packet);
String thePacket = readPacket();
return thePacket;
}
..................
我的問題是關於writePacket方法的簽名。變量數據包必須聲明爲最終的或編譯器抱怨,因爲SwingWorker是一個內部類。這引發了以下問題:我如何以及何時可以爲這個變量賦值:在Java SwingWorker方法簽名中使用final變量
- 最後我意味着變量只能賦值一次。但是由於聲明是方法簽名的一部分,我不知道在這種情況下這意味着什麼。
- 我始終認爲最終變量是在類實例化時賦值的,但是在調用該方法時在這裏賦值。傳遞給方法的變量是否也需要聲明爲final並在類的構造函數中分配以使其工作?
- 我可以多次調用該方法使用不同的數據包值,或者因爲變量被聲明爲final,這是否意味着如果我想用不同的值調用方法,我需要重新實例化每個新值的類變量數據包?
在此先感謝您的幫助。
埃利奧特
請閱讀http://stackoverflow.com/questions/7053865/cant-get-arrayindexoutofboundsexception-from-future-and-swingworker-if-thread,...以避免從SwingWorker&Future >丟失錯誤,特別是post通過@trashgod – mKorbel