이하이 싶습니다.
다음 예에서는 병렬 처리 할 프로세서와 같은 역할을하는 다른 도우미 클래스를 사용하는 기본 클래스를 만들었습니다.
메인 클래스는 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;
}
}
희망.
Java fork/join 프레임 워크의 도움을받을 수 있습니다. Java7 의 일부입니다 .https : //docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html –
wait() 및 notify() 메소드를 살펴볼 수도 있습니다 –