다중 스레드를 사용하는 방법을 이해하려고합니다. 나는 i
의 값을 증가시키는 간단한 프로그램을 작성했다. 두 개의 방법을 사용하여 400,000 번 : 단일 스레드 방식 (0에서 400,000)과 다중 스레드 방식 (제 경우에는 4 번 : 0에서 100,000까지)을 숫자와 함께 사용한다. 스레드의 Runtime.getRuntime().availableProcessors()
와 같습니다.java - 단일 스레드보다 다중 스레드에서 간단한 계산이 더 걸림
내가 측정 한 결과에 놀랐습니다. 단일 스레드 방식은 확실히 빨라졌으며 때로는 3 배 빨랐습니다.
Computation time using 4 threads : 10ms.
Computation time using main thread : 3ms.
사람이 설명 할 수 없습니다 :
public class Main {
public static int LOOPS = 100000;
private static ExecutorService executor=null;
public static void main(String[] args) throws InterruptedException, ExecutionException {
int procNb = Runtime.getRuntime().availableProcessors();
long startTime;
long endTime;
executor = Executors.newFixedThreadPool(procNb);
ArrayList<Calculation> c = new ArrayList<Calculation>();
for (int i=0;i<procNb;i++){
c.add(new Calculation());
}
// Make parallel computations (4 in my case)
startTime = System.currentTimeMillis();
queryAll(c);
endTime = System.currentTimeMillis();
System.out.println("Computation time using " + procNb + " threads : " + (endTime - startTime) + "ms");
startTime = System.currentTimeMillis();
for (int i =0;i<procNb*LOOPS;i++)
{
}
endTime = System.currentTimeMillis();
System.out.println("Computation time using main thread : " + (endTime - startTime) + "ms");
}
public static List<Integer> queryAll(List<Calculation> queries) throws InterruptedException, ExecutionException {
List<Future<Integer>> futures = executor.invokeAll(queries);
List<Integer> aggregatedResults = new ArrayList<Integer>();
for (Future<Integer> future : futures) {
aggregatedResults.add(future.get());
}
return aggregatedResults;
}
}
class Calculation implements Callable<Integer> {
@Override
public Integer call() {
int i;
for (i=0;i<Main.LOOPS;i++){
}
return i;
}
}
콘솔 : 여기 내 코드는?
당신이 멀티 스레드에서 너무 많은 일을 생각하지 않는다? 미래를 창조하고, 미래를리스트에 추가합니까? 또한 다중 스레드는 항상 단일 스레드보다 좋을 것이라는 필수 사항은 아닙니다. – SMA
여러 스레드를 만드는 것이 값을 늘리는 것보다 오래 걸리는 것 같습니다. – peterremec
물론 멀티 스레딩에는 오버 헤드가 있습니다. 멀티 스레딩 이점을 얻을만큼 큰 문제가 필요합니다. 또한 플랫폼, 하드웨어 (멀티 코어) 및 구현 (Java8 스트림은 멀티 코어를 많이 사용할 수 있음)에 따라 다릅니다. – PeterMmm