Passing Parameters to a Thread

Issue: BAEL-2417
This commit is contained in:
sandy03934 2018-12-23 01:04:29 +05:30 committed by Josh Cummings
parent e0d24b6780
commit 0459f337cd
3 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package com.baeldung.concurrent.parameter;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;
public class AverageCalculator implements Callable<Double> {
int[] numbers;
public AverageCalculator(int... parameter) {
this.numbers = parameter == null ? new int[0] : parameter;
}
@Override
public Double call() throws Exception {
return IntStream.of(this.numbers)
.average()
.orElse(0d);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.concurrent.parameter;
import java.util.concurrent.Callable;
import java.util.stream.IntStream;
public class ParameterizedThreadExample {
public static void parameterisedThreadAnonymousClass() {
final String parameter = "123";
Thread parameterizedThread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread()
.getName() + " : " + parameter);
}
});
parameterizedThread.start();
}
public static Callable<Integer> sumCalculator(int... numbers) {
return () -> numbers != null ? IntStream.of(numbers)
.sum() : 0;
}
public static Callable<Double> averageCalculator(int... numbers) {
return () -> numbers != null ? IntStream.of(numbers)
.average()
.orElse(0d) : 0d;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.parameters;
import com.baeldung.concurrent.parameter.AverageCalculator;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.IntStream;
import static org.junit.Assert.assertEquals;
public class ParameterizedThreadUnitTest {
@Test
public void whenSendingParameterToCallable_thenSuccessful() throws Exception {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Double> result = executorService.submit(new AverageCalculator(1, 2, 3));
try {
assertEquals(Double.valueOf(2.0), result.get());
} finally {
executorService.shutdown();
}
}
@Test
public void whenParametersToThreadWithLamda_thenParametersPassedCorrectly() throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(2);
int[] numbers = new int[] { 4, 5, 6 };
try {
Future<Integer> sumResult = executorService.submit(() -> IntStream.of(numbers)
.sum());
Future<Double> averageResult = executorService.submit(() -> IntStream.of(numbers)
.average()
.orElse(0d));
assertEquals(Integer.valueOf(15), sumResult.get());
assertEquals(Double.valueOf(5.0), averageResult.get());
} finally {
executorService.shutdown();
}
}
}