如何将参数传递给ThreadManager.createThreadForCurrentRequest(GAE中的new Runnable()?

时间:2013-06-13 05:41:17

标签: java multithreading google-app-engine

如何将参数传递给Thread

陈述log( "before process , counter = " + i); 导致错误:

  

不能引用在不同方法中定义的内部类中的非final变量i

请帮助

for (int i = 0; i < 20; i++) {
    Thread thread = ThreadManager.createThreadForCurrentRequest(new Runnable() {
        public void run() {
            try {
                log("before process , counter = " + i);
                Thread.sleep(1000);
                log("after process  ,      "  + "counter = " + i);

            } catch (InterruptedException ex) {
                throw new RuntimeException("Interrupted in loop:", ex);
            }
        }
    });
    thread.start();
}

2 个答案:

答案 0 :(得分:0)

正如它所说,只是一个最终变量。这告诉Java它不会被更改,它可以安全地用在Runnable中。

for (int i = 0; i < 20; i++) {
    final int counter=i;

答案 1 :(得分:0)

你需要这样做:

for (int i = 0; i < 20; i++) {
    final int counter = i;
    // etc
}

然后在你的线程中使用counter而不是i(正如错误消息告诉你的那样,这不是最终的,因此在这种情况下不能使用)。

相关问题