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