Explain Codes LogoExplain Codes Logo

Runnable with a parameter?

java
lambda
functional-programming
thread-management
Anton ShumikhinbyAnton Shumikhin·Jan 19, 2025
TLDR
@FunctionalInterface interface ParamRunnable<T> { void run(T param); } // A loud "Hello" to the world! ParamRunnable<String> display = message -> System.out.println(message); display.run("Hello!"); // Output: Hello!

You can pass the ParamRunnable like a relay baton. This custom functional interface surfs with parameters on lambda waves, mimicking a parameterized Runnable.

Unleash the Lambda within Runnable

Java 8 swung the doors open for lambda expressions, painting a Picasso portrait of parenthetical elegance. Ponder this:

String param = "Not just multitasking, but efficient multitasking!"; // Starting a secret Lambda revolution, Shh! new Thread(() -> System.out.println("My secret mission: " + param)).start();

Mastering Lambdas is like unlocking a new skill in a video game – it's pure adrenaline.

Thread Pool: The Fellowship of the Runnable

Time to transition to Java ExecutorService for better thread management! It's like having a superstar team of threads at your disposal.

ExecutorService executor = Executors.newFixedThreadPool(10); // Assemble the Avengers! executor.submit(() -> task.run(customParameter));

Hey Consumer! Over here

Unmask the Consumer<T> - a functional interface tailored to accept a single input argument. Think of it as a gift, it’s made to be unwrapped.

Consumer<Integer> consumerRunnable = (Integer param) -> System.out.println("Say hello to my little param: " + param); consumerRunnable.accept(42); // Output: Say hello to my little param: 42

Stealth mode: Encapsulation

Compile an init() method or a constructor for parameter encapsulation. It's just your Runnable pulling some James Bond moves.

class ParamRunnable implements Runnable { private String param; public ParamRunnable(String param) { this.param = param; } public void run() { System.out.println("Mission: " + param); // Mission impossible? } } new Thread(new ParamRunnable("Go Stealth!")).start();

Streamline Runnable creation

Leverage the factory pattern to produce Runnable instances as Monty Python churns out laughs.

public static Runnable createRunnableWithParam(String param) { return () -> System.out.println("Joke's on you, the param is: " + param); }

Just call createRunnableWithParam("Why was the computer cold? It left the Windows open!") and blink twice, it's that easy.

Object-Oriented Runway

Take a stroll down Object-Oriented boulevard with getters and setters:

class ParameterizedRunnable implements Runnable { private Object[] params; // Params are like clothing, vary with every outing public void setParams(Object... newParams) { this.params = newParams; } public Object[] getParams() { return this.params; // Dress code: Params casual } public void run() { // Use 'params' in a stylish way } }

Designer Runnables

Need Runnable instances for every occasion? Store these trendy Runnables in a hashmap for effortless mix and match:

Map<String, Runnable> tasks = new HashMap<>(); tasks.put("tuxedo", createRunnableWithParam("Suited up!")); tasks.put("pajamas", createRunnableWithParam("Bedtime stories."));

Parametric fashion in Java

There's no 'one-style-fits-all' in Java. Check out Function<T,R>, Supplier<T>, BiConsumer<T,U> each functioning as a stylish millennial adapting to change.

Runnable: The Extensible Edition

Get adventurous with an extendable Runnable. Flexibility at its finest:

public abstract class ParametrizedRunnable implements Runnable { // Overridable method making params more dynamic than a Cirque du Soleil performance! public abstract void runWithParams(Object... params); @Override public void run() { // Make run behave differently based on params runWithParams(); } }

Having a Matrix moment? Pick the efficient pill

Channeling the power of parameterized Runnable can make your system performance go from Clark Kent to Superman. Just remember, (thread) power responsibly!

Cut the cord with function methods

Time to revisit function method. This approach is like playing Tetris, you fit tasks in the right gaps:

Function<String, Runnable> createPrinter = message -> () -> System.out.println(message); Runnable helloPrinter = createPrinter.apply("Hello"); new Thread(helloPrinter).start();