如何在具有线程安全性的多个swing工作线程中使用Instance变量?

时间:2013-10-29 07:36:51

标签: java multithreading swing swingworker

我正在使用swing工作线程来传达休息服务。我的场景是我正在调用一个线程来从其他服务获取数据并添加到我的列表变量中。 和另一个线程来推送数据列表以保存它。如何使用线程安全处理此场景

我的示例代码位于

之下
  private LinkedList<LinkInfo> ***linkInfoList*** = new LinkedList<FlowLinkEntry>();

 SwingWorker<LinkInfo, Void> loadLinkInfoThread = new SwingWorker<LinkInfo, Void>() {

        @Override
        protected LinkInfo doInBackground() throws Exception {

            InputStream is = new URL("Http://URL").openStream();
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is,
                                Charset.forName("UTF-8")));
                LinkInfo linkInfo = (LinkInfo)JsonConverter
                        .fromJson(reader, LinkInfo.class);
                ***linkInfoList*** .add(linkInfo);

            } finally {
                is .close();
            }
            return linkInfo;
        }
}


 SwingWorker<Void, Void> saveLinkInfoThread = new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            //post data to particular url   
            //linkInfoList data is posting in this thread 

            URL url = new URL(http://url);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(***linkInfoList*** );
            wr.flush();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));

        }

}

我的问题是

  1. 如何将数据作为请求顺序存储在linkInfoList中? (即)如果我多次调用加载线程,数据应该明确地插入列表中。

  2. 如果加载线程是,如何将等待状态置于保存线程中     已经在进行中。我的意思是如果加载线程在     运行条件,完成加载线程后,只需保存线程就必须运行

1 个答案:

答案 0 :(得分:1)

我会在初始化时将列表同步为Oracle says

List ***linkInfoList*** = Collections.synchronizedList(new LinkedList(...));

如果有任何要保存的项目,则必须测试列表,否则等待。

SwingWorker<Void, Void> saveLinkInfoThread = new SwingWorker<Void, Void>() {

    @Override
 protected Void doInBackground() throws Exception {

      List info = new ArrayList();
      while (***linkInfoList***.isEmpty()){
           Thread.currentThread().sleep(1000);
      }
      while (!***linkInfoList***.isEmpty()){
           info.add(***linkInfoList***.remove(0));
      }



      //post data to particular url   
      //linkInfoList data is posting in this thread 

      URL url = new URL(http://url);
      URLConnection conn = url.openConnection();
      conn.setDoOutput(true);
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());


      wr.write(info);
      wr.flush();
      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(
      conn.getInputStream()));

    }