2017-11-23 3 views
3

다음과 같은 코드가 있습니다. 루프에서 메소드 "프로세스"를 실행 중입니다. 순차적으로 실행됩니다.이 메서드를 병렬로 실행하고 싶지만 다음 줄에서 더할 수 있도록 루프 내에서 완료되어야합니다. 즉, 두 번째 for 루프가 실행되기 전에 모든 함수가 완료되어야하는 병렬로 실행 중이다. 누구든지 JDK1.8version이 아닌 Jdk1.7에서 해결 방법을 도울 수 있습니까?자바를 사용하여 루프 내에서 병렬로 메소드를 실행하십시오.

public static void main(String s[]){ 
    int arrlen = 10; 
    int arr[] = new int[arrlen] ; 

    int t =0; 
    for(int i=0;i<arrlen;i++){ 
     arr[i] = i; 
     t = process(arr[i]); 
     arr[i] = t; 
    } 

    int sum =0; 
    for(int i=0;i<arrlen;i++){ 
     sum += arr[i]; 
    } 
    System.out.println(sum); 

} 

public static int process(int arr){ 
    return arr*2; 
} 
+0

Java fork/join 프레임 워크의 도움을받을 수 있습니다. Java7 의 일부입니다 .https : //docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html –

+0

wait() 및 notify() 메소드를 살펴볼 수도 있습니다 –

답변

3

아래의 예는 도움이 될 수 있습니다. 나는 그것을하기 위해 fork/join 프레임 워크를 사용했다.

예와 같이 작은 배열 크기의 경우 기존 방법이 더 빠를 수 있으며 포크/조인 방식이 다소 시간이 오래 걸릴 것으로 생각됩니다. 그러나 더 큰 크기 또는 프로세스의 경우, 포크/조인 프레임 워크가 적합합니다. 자바 8 병렬 스트림조차 기본 기반으로 포크/조인 프레임 워크를 사용합니다.

public class ForkMultiplier extends RecursiveAction { 
     int[] array; 
     int threshold = 3; 
     int start; 
     int end; 

     public ForkMultiplier(int[] array,int start, int end) { 
      this.array = array; 
      this.start = start; 
      this.end = end; 
     } 

     protected void compute() { 
      if (end - start < threshold) { 
       computeDirectly(); 
      } else { 
       int middle = (end + start)/2; 
       ForkMultiplier f1= new ForkMultiplier(array, start, middle); 
       ForkMultiplier f2= new ForkMultiplier(array, middle, end); 
       invokeAll(f1, f2); 
      } 
     } 

     protected void computeDirectly() { 
      for (int i = start; i < end; i++) { 
       array[i] = array[i] * 2; 
      } 
     } 
    } 

당신은 메인 클래스 당신은 기본적으로 실행 프로그램과 자바 1.5 (Java Documentation 참조) 때문에 존재하는 결합 선물을 사용할 필요가

public static void main(String s[]){ 

     int arrlen = 10; 
     int arr[] = new int[arrlen] ; 


     for(int i=0;i<arrlen;i++){ 
      arr[i] = i; 
     } 

     ForkJoinPool pool = new ForkJoinPool(); 
     pool.invoke(new ForkMultiplier(arr, 0, arr.length)); 

     int sum =0; 
     for(int i=0;i<arrlen;i++){ 
      sum += arr[i]; 
     } 

     System.out.println(sum); 

    } 
0

이하이 싶습니다.

다음 예에서는 병렬 처리 할 프로세서와 같은 역할을하는 다른 도우미 클래스를 사용하는 기본 클래스를 만들었습니다.

메인 클래스는 3 단계에서 스플릿된다

  1. 는 프로세스 풀을 생성하고 병렬로 작업을 수행한다.
  2. 모든 작업이 끝나기를 기다립니다.
  3. 작업의 결과를 수집합니다. 교훈적인 이유로

, 나는 일부 로그를 넣어 더 중요했다, 나는 프로세스별로 시간이 소요되는 알고리즘으로 실행을 시뮬레이션, 각 프로세스 '비즈니스 로직에서 임의의 대기 시간을 넣었습니다.

병렬 작업 수를 늘린 경우에도 각 프로세스의 최대 대기 시간은 2 초이며 2 단계에서 가장 높은 대기 시간입니다 (다음 코드의 변수 totalTasks을 테스트 해보십시오) . 여기

메인 클래스 : 여기 Process 클래스

package com.example; 

import java.util.ArrayList; 
import java.util.concurrent.ExecutionException; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.Future; 

public class Main 
{ 
    public static void main(String[] args) throws InterruptedException, ExecutionException 
    { 
     int totalTasks = 100; 

     ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(totalTasks); 

     System.out.println("Step 1 - Starting parallel tasks"); 

     ArrayList<Future<Integer>> tasks = new ArrayList<Future<Integer>>(); 
     for (int i = 0; i < totalTasks; i++) { 
      tasks.add(newFixedThreadPool.submit(new Process(i))); 
     } 

     long ts = System.currentTimeMillis(); 
     System.out.println("Step 2 - Wait for processes to finish..."); 

     boolean tasksCompleted; 
     do { 
      tasksCompleted = true; 

      for (Future<Integer> task : tasks) { 
       if (!task.isDone()) { 
        tasksCompleted = false; 
        Thread.sleep(10); 
        break; 
       } 
      } 

     } while (!tasksCompleted); 

     System.out.println(String.format("Step 2 - End in '%.3f' seconds", (System.currentTimeMillis() - ts)/1000.0)); 

     System.out.println("Step 3 - All processes finished to run, let's collect results..."); 

     Integer sum = 0; 

     for (Future<Integer> task : tasks) { 
      sum += task.get(); 
     } 

     System.out.println(String.format("Total final sum is: %d", sum)); 
    } 
} 

:이 도움이

package com.example; 

import java.util.concurrent.Callable; 

public class Process implements Callable<Integer> 
{ 
    private Integer value; 

    public Process(Integer value) 
    { 
     this.value = value; 
    } 

    public Integer call() throws Exception 
    { 
     Long sleepTime = (long)(Math.random() * 2000); 

     System.out.println(String.format("Starting process with value %d, sleep time %d", this.value, sleepTime)); 

     Thread.sleep(sleepTime); 

     System.out.println(String.format("Stopping process with value %d", this.value)); 

     return value * 2; 
    } 
} 

희망.

관련 문제