public interface Runnable {
public void run();
}
public class LoggingTask implements Runnable {
private Logger logger
= LoggerFactory.getLogger(LoggingTask.class);
@Override
public void run() {
logger.info("Hello");
}
}
public void execute() {
exeService = Executors.newSingleThreadExecutor();
Future future = exeService.submit(new LoggingTask());
exeService.shutdown();
}
public interface Callable<V> {
V call() throws Exception;
}
public class FactorialTask implements Callable<Integer> {
int number;
// стандартные конструкторы
public Integer call() throws InvalidParamaterException {
int factor = 1;
// ...
for(int count = number; count > 1; count--) {
factor = factor * count;
}
return factor;
}
}
@Test
public void whenTaskSubmitted_ThenFutureResultObtained(){
FactorialTask task = new FactorialTask(7);
Future<Integer> future = executorService.submit(task);
assertEquals(5040, future.get().intValue());
}
public class FactorialTask implements Callable<Integer> {
public Integer call() throws InvalidParamaterException {
if(number < 0) {
throw new InvalidParamaterException("This should be positive");
}
}
}
@Test(expected = ExecutionException.class)
public void whenException_ThenCallableThrowsIt() {
FactorialCallableTask task = new FactorialCallableTask(-4);
Future<Integer> future = executorService.submit(task);
Integer result = future.get().intValue();
}
@Test
public void whenException_ThenCallableDoesntThrowsItIfGetIsNotCalled(){
FactorialCallableTask task = new FactorialCallableTask(-4);
Future<Integer> future = executorService.submit(task);
assertEquals(false, future.isDone());
}