added ex Q2

This commit is contained in:
Louis Heredero 2024-12-17 15:28:34 +01:00
parent 532a727b43
commit 508d412a1a
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
2 changed files with 62 additions and 0 deletions

View 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();
}
}

View 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."
);
}
}