仿照网上写了一个方法 统计n个线程同时调一个方法,都执行完需要多长时间 ,发现一个奇怪的问题
package me.ele.coffe.hr.stress.test;
public class test {
private static Integer error = 0;
private static Integer threads = 40;
private static Long startTime;
private static Long endTime;
public static void main(String[] args) {
System.out.println("begin testing");
System.out.println("线程数" + threads) ;
WorkThread[] workThreads = new WorkThread[threads];
for (int i = 0; i < threads; i++) {
workThreads[i] = new WorkThread();
}
startTime = System.currentTimeMillis();
for (int i = 0; i < threads; i++) {
workThreads[i].start();
}
}
private static class WorkThread extends Thread {
public void run() {
try {
//要测试的函数
String s = testFunctoin.testString();
} catch (Exception e) {
synchronized (error) {
error++;
}
e.printStackTrace();
}
synchronized (threads) {
System.out.println("当前运行线程:====================" + getName());
threads--;
if (threads == 0) {
endTime = System.currentTimeMillis();
System.out.printf("总耗时:%d毫秒\n",endTime - startTime);
System.out.printf("连接失败数量:%d\n", error);
}
}
}
}
}
发现当线程数较小时 可以打印出总耗时和连接失败数量
但当线程数较大时(比如40),就打印不出来了。。。
求帮忙看看 有没有哪里写的不对
Here’s the problem
When the thread starts, the value of threads in the for loop becomes smaller and smaller, so your thread has not finished executing. Just replace threads with a final constant.
This is the reason for threads. Your main thread main has the same thread count as the thread used. Therefore, when threads specifies 40, 40 threads may not be opened. It may appear as follows:
23 threads have been opened previously and completed before the for operation of the main thread main, then at this time
i = 23, threads = 23,
Therefore, the thread will no longer be opened, so threads cannot be equal to 0, so output cannot be performed!
I personally recommend using executor and future to write threads, and you can learn about it through atomicinteger counting!