在不同线程中的类之间传递对象的最佳方法?

时间:2013-04-15 11:16:01

标签: java

我有一个“可运行”的类“A”,我用Java unmarshallers创建新对象。 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();

}

2 个答案:

答案 0 :(得分:3)

尝试Producer-Consumer模式。

答案 1 :(得分:0)

您可以在main中声明类型为“A”的引用,并将其传递给另一个线程。 在另一个线程中执行操作并将新的A实例分配给引用。 像这样的东西

A aVariable;
Thread t = new Thread(new MyThread(aVariable));
t.start();
t.join();
populateGUI(aVariable);