0

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

我的示例代码如下

  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. 如果加载线程已经在进行中,如何将等待状态置于保存线程。我的意思是,如果加载线程处于运行状态,则在完成加载线程后,只需要运行保存线程

4

1 回答 1

1

正如Oracle 所说,我会在初始化时同步列表。

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()));

    }
于 2013-10-29T08:00:21.897 回答