package tryAny.effectiveJava;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ExecutorTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Callable<String>> tasks = Arrays.asList(() -> "first", () -> "second");
ExecutorService es = Executors.newFixedThreadPool(2);
List<Future<String>> rets = es.invokeAll(tasks);
for (Future<String> r : rets) {
System.out.println(r.get());
}
System.out.println(es.invokeAny(tasks));//premier ou deuxième au hasard
}
}
package tryAny.concurrentUtility;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
//Continue à générer des valeurs aléatoires toutes les secondes.
public class ConcurrentTest6 {
public static void main(String[] args) {
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1);
ScheduledFuture<?> sf = stpe.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println(Math.random());
}
}, 1000, 1000, TimeUnit.MILLISECONDS);
while (true) {
if (sf.isCancelled() || sf.isDone()) {
stpe.shutdown();
break;
}
}
}
}
package tryAny.concurrentUtility;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class ConcurrentTest8 {
public static void main(String[] args) {
int data[] = { 1, 2, 3, 4, 5, 6, 7 };
ForkJoinPool service = new ForkJoinPool();
service.invoke(new AddAction(data, 0, data.length));
}
}
class AddAction extends RecursiveAction {
private static final int THRESHOLD_SIZE = 3;
private int start;
private int end;
private int[] numbers;
public AddAction(int[] numbers, int start, int end) {
this.start = start;
this.end = end;
this.numbers = numbers;
}
protected void compute() {
int total = 0;
if (end - start <= THRESHOLD_SIZE) {
for (int i = start; i < end; i++) {
total += numbers[i];
}
System.out.println(total + " ");
} else {
new AddAction(numbers, start + THRESHOLD_SIZE, end).fork();
new AddAction(numbers, start, Math.min(end, start + THRESHOLD_SIZE)).compute();
}
}
}
Recommended Posts