当前位置: 动力学知识库 > 问答 > 编程问答 >

Java Multithreading With For Loops Issue

问题描述:

I have an odd issue.

I create and run a new thread like so:

for (int i = 0; i < TIMES_TO_CALL_PING; i++) {

new Thread(new Runnable() {

public void run() {

try {

Process p = Runtime.getRuntime().exec(

"ping -l " + PACKET_SIZE + " -n "

+ TIMES_TO_PING_PER_CALL + " "

+ ADDRESS);

BufferedReader in = new BufferedReader(

new InputStreamReader(p.getInputStream()));

String input;

while ((input = in.readLine()) != null) {

if (input.contains("time=")) {

totalPingTime += Integer.parseInt(input

.split("time=")[1].split("ms")[0]);

average = (double) (totalPingTime / index);

pingTime.setText("Average Ping Time: "

+ average + "ms");

System.out.println(index);

}

output.append(input + "\n");

}

} catch (IOException e) {

e.printStackTrace();

}

}

}).start();

index = i;

pingCount.setText("Pings called: " + (i + 1));

frame.pack();

}

And the output of the program is:

http://pastebin.com/E2fjczSq

Notice how the program prints "9999" forever (it never stops) and how the numbers aren't in order like 1, 2, 3, 4, 5. Why is this happening?

网友答案:

In order to capture index variable value for each thread on thread start, rewrite thread instantiation to following:

class OVThread extends Thread {

    int index;

    public OVThread(int index, Runnable target) {
        super(target);
        this.index = index;
    }

}

Now you can use it as this:

for (int i = 0; i < TIMES_TO_CALL_PING; i++) {
    new OVThread(index, new Runnable() {

            @Override
            public void run() {
                try {
                    ...
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    ...
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: