有2部分。我使用google app engine java。 1,任务队列,启动2个进程
2,每个进程使用ThreadManager.createThreadForCurrentRequest(new Runnable(){ for 2 Thread
我希望设置" total_i" Thread的值基于(int i_from,int i_to)。 当将值(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;
}
}
}