从不同的线程填充数组

1 java static multithreading

我正在尝试编写一个非常简单的程序,它创建了几个线程来将并发请求发送到特定的URL.我测量并存储响应时间.我遇到的问题是,尽管我将响应时间数组创建为静态和最终,但是我存储在此数组中的值仅在我生成一个生成的线程时才存在.一旦我离开循环并进入主线程,数组就为空(包含0个值).所以我的代码片段中的总和始终为零.我意识到我的错误可能是一个非常基本的错误,但不幸的是我无法在网上找到类似的主题.你能指点我正确的方向吗?谢谢.

public class MyClass {      
static final long[] respTimes = new long[l];

public static void sendRequest() {...}

public static void main(String[] args) throws Exception {  
    for(int i=0; i<l; i++) {
        new Thread("" + i) {
            public void run() { 
                long startTime = System.nanoTime();
                sendRequest();
                long estimatedTime = System.nanoTime() - startTime;
                respTimes[i] = estimatedTime;
            }
        }.start();
    }
        for(int i=0; i<l; i++) { sum += respTimes[i]; }
}  
Run Code Online (Sandbox Code Playgroud)

}

ilu*_*uxa 7

那不是问题.您的问题是您在有机会生成结果之前打印出结果.做这个:

Thread [] theThreads = new Thread[10];

for (...) {
  theThreads[i] = new Thread() { ... }.start();
}

// now make sure all the threads are done
for (...) {
  // this waits for the thread to finish
  theThreads[i].join();
}

// now print things out
Run Code Online (Sandbox Code Playgroud)