added ex Q2
This commit is contained in:
parent
532a727b43
commit
508d412a1a
34
src/exercises/ex_q2/CustomRecursiveAction.java
Normal file
34
src/exercises/ex_q2/CustomRecursiveAction.java
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package exercises.ex_q2;
|
||||||
|
|
||||||
|
import java.util.concurrent.RecursiveAction;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
public class CustomRecursiveAction extends RecursiveAction {
|
||||||
|
private static final int threshold = 10;
|
||||||
|
private String song;
|
||||||
|
|
||||||
|
public CustomRecursiveAction(String song) {
|
||||||
|
this.song = song;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void compute() {
|
||||||
|
Logger logger = Logger.getAnonymousLogger();
|
||||||
|
if (song.length() <= threshold) {
|
||||||
|
logger.info("Splitting problem");
|
||||||
|
changeToUppercase();
|
||||||
|
} else {
|
||||||
|
logger.info("Problem is small enough");
|
||||||
|
int halfSize = song.length() / 2;
|
||||||
|
CustomRecursiveAction task1 = new CustomRecursiveAction(song.substring(0, halfSize));
|
||||||
|
CustomRecursiveAction task2 = new CustomRecursiveAction(song.substring(halfSize));
|
||||||
|
invokeAll(task1, task2);
|
||||||
|
song = task1.song + task2.song;
|
||||||
|
logger.info("Solution: " + song);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void changeToUppercase() {
|
||||||
|
song = song.toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
28
src/exercises/ex_q2/ForkJoinTest.java
Normal file
28
src/exercises/ex_q2/ForkJoinTest.java
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package exercises.ex_q2;
|
||||||
|
|
||||||
|
import java.util.concurrent.ForkJoinPool;
|
||||||
|
|
||||||
|
public class ForkJoinTest {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String song = "Georges Brassens (1964) - Les Copains d'abord"
|
||||||
|
+ "Non, ce n'était pas le radeau"
|
||||||
|
+ "De la Méduse, ce bateau"
|
||||||
|
+ "Qu'on se le dise au fond des ports"
|
||||||
|
+ "Dise au fond des ports"
|
||||||
|
+ "Il naviguait en père peinard"
|
||||||
|
+ "Sur la grand-mare des canards"
|
||||||
|
+ "Et s'appelait les Copains d'abord"
|
||||||
|
+ "Les Copains d'abord";
|
||||||
|
int processors = Runtime.getRuntime().availableProcessors();
|
||||||
|
System.out.println("Number of available processors: " + processors);
|
||||||
|
ForkJoinPool pool = new ForkJoinPool(processors);
|
||||||
|
long startTime = System.currentTimeMillis();
|
||||||
|
pool.invoke(new CustomRecursiveAction(song));
|
||||||
|
long endTime = System.currentTimeMillis();
|
||||||
|
System.out.println(
|
||||||
|
"Fork/Join tasks took "
|
||||||
|
+ (endTime - startTime)
|
||||||
|
+ " milliseconds."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user