2013-04-15 35 views
5

我有一个类“A”,它是“可运行的”,并且我从Java卸载器中创建新的对象。 MainGUI线程尝试通过已经在类“A”中的get()来访问这些实例。我在A类创建的实例中,我使它们成为静态的,以便它们永远可用,但是当我得到具有不同属性的新的完整实例时,我必须将新实例与先前的一个数据进行比较,并保留新的那一个。在不同线程中的类之间传递对象的最佳方式?

有没有更好的方法或设计的问题?

如何获取在运行时创建的类“A”的实例而不使其静态?

示例代码:

public class SOAPMessagesFactory { 

    private static GetCameraImageResponse    getCameraImageResponse; 

// process here the msgs in another thread, not shown here in that snipped 
    if (messageTag.equalsIgnoreCase("GetCameraImageResponse")) { 
       try { 
        JAXBElement<GetCameraImageResponse> cameraImageResponse = unmarshaller.unmarshal(SoapBodyReader, GetCameraImageResponse.class); 
        getCameraImageResponse = cameraImageResponse.getValue(); 

       } catch (Throwable ex) { 
        ex.printStackTrace(); 
       } 

      } 

public GetCameraImageResponse getCameraImageResponse() { 

    if (getCameraImageResponse != null) { 
     return getCameraImageResponse; 
    } else { 
     return null; 
    } 

} 
    // in main gui 

public void UpdateGUI() { 

     GetCameraImageResponse cameraImageResponse = messageFactory.getCameraImageResponse(); 

} 
+0

你以前的一个数据是什么意思,并保留新的数据?你正在更换实例吗? –

+0

OP意味着他想保持最后一个对象(用于比较)和新的对象 – Freak

+0

你能提供代码片段吗? –

回答

0

你可以申报主要类型为“A”的参考,并传递给其他线程。 在另一个线程中执行操作并将A的新实例分配给引用。 像这样

A aVariable; 
Thread t = new Thread(new MyThread(aVariable)); 
t.start(); 
t.join(); 
populateGUI(aVariable); 
相关问题