0

有 2 部分。我正在使用谷歌应用引擎 java。1、task Queue,启动2个进程

2、每个进程使用ThreadManager.createThreadForCurrentRequest(new Runnable() { for 2 Thread

我希望根据 (int i_from, int i_to) 由 Thread 设置“total_i”值。当将值 (1,2) 和 (3,4) 传递给每个线程时,total_i 的总数应该是 6 和 14。但是 2 个线程给了我相同的值 14。我真的很困惑,需要帮助。谢谢

//part 1 : 

total_count = 4; // temp set
record_count= 2;
Queue queue = QueueFactory.getDefaultQueue();
// queue 分段读取 detail data, 每次30个
for (int i = 1; i <= total_count; i += record_count) {
  code_from = String.valueOf(i);
  code_to = String.valueOf(i + record_count - 1);
      queue.add(TaskOptions.Builder.withUrl("/test_DetailDown").method(TaskOptions.Method.GET).param("from", code_from).param("to", code_to));

}

//part 2:

    @SuppressWarnings("serial")
    public class test_DetailDown extends HttpServlet {
      AtomicInteger counter = new AtomicInteger();
      final static int ThreadCount = 2;
      int[] recordArr = new int[ThreadCount];

      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, DeadlineExceededException {

        resp.getWriter().println("start");
        // this is called by "Queue_Detail_Down" from Queue with parameter : from,
        // to
        String code_from = req.getParameter("from");
        String code_to = req.getParameter("to");

        TodayDetail(Integer.valueOf(code_from), Integer.valueOf(code_to)); 
        // process to down data
      }

      // this is the process to get today datail
      private void TodayDetail(int code_from, int code_to) {

        int total_i = 0;

        // int record_count = 2;

        // loop symbol to get detail data from stock.zaobao
        for (int i = 0; i < ThreadCount; i++) {

          final int i_from = code_from; // pass parameter
          final int i_to = code_to;
          // thread
          Thread thread = ThreadManager.createThreadForCurrentRequest(new Runnable() {
            public void run() {
              counter.incrementAndGet();
              get_detail_data(i_from, i_to); // down web data
              counter.decrementAndGet();
            }
          });
          thread.start(); // end thread process
        }
        // wait all thread
        while (true) {
          int num = counter.get();
          if (num <= 0)
            break;
          try {
            Thread.sleep(300);
          } catch (InterruptedException ex) {
          }
        }
        // save data
        for (int i = 0; i < ThreadCount; i++) {
          total_i = total_i + recordArr[i];
        }
        System.out.println("after Thread process, total_i =" + total_i);
        log("end of program");
      }

      // core process, get data
      private void get_detail_data(int i_from, int i_to) {

        for (int i = 0; i < ThreadCount; i++) {
          recordArr[i] = i_from + i_to;
        }

      }
    }
4

0 回答 0