Skip to content
Snippets Groups Projects
Commit 6de46eb7 authored by Jan Kožusznik's avatar Jan Kožusznik
Browse files

solution

parent d52ec73b
No related merge requests found
Pipeline #106 failed with stages
in 0 seconds
package koz01.java2.lab07;
import java.math.BigInteger;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class TestThreads {
@Test
public void tenRandomCalls() throws InterruptedException {
ExecutorService es = Executors.newWorkStealingPool();
runExecutions(es);
es.shutdown();
}
public void tenRandomThreads() throws InterruptedException {
long testStart = System.currentTimeMillis();
Collection<Thread> threads = new LinkedList<>();
for(int i = 0; i < 10; i++) {
final int thread_n = i;
Thread t = new Thread() {
@Override
public void run() {
//zde může být nějaký super výpočet
long start = System.currentTimeMillis();
Random rnd = new Random();
int sleep = rnd.nextInt(3000) + 2000;
try {
TimeUnit.MILLISECONDS.sleep(sleep);
}
catch (InterruptedException exc) {
log.error("sleep", exc);
}
long delta = System.currentTimeMillis() - start;
log.info("Thread: #{}, duration = {}", thread_n, delta);
}
};
threads.add(t);
t.start();
}
threads.forEach(t -> {
try {
t.join();
}
catch (InterruptedException exc) {
log.error("join", exc);
}
});
log.info("Test duration = {}", System.currentTimeMillis() - testStart);
}
private void runExecutions(ExecutorService es) {
Collection<Future<Long>> futures = new LinkedList<>();
long testStart = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
Callable<Long> t = new Callable<>() {
@Override
public Long call() {
long start = System.currentTimeMillis();
// zde může být nějaký super výpočet
BigInteger bi = BigInteger.ONE;
for (int i = 2; i < 50000; i++) {
bi = bi.multiply(BigInteger.valueOf(i));
}
long delta = System.currentTimeMillis() - start;
return delta;
}
};
Future<Long> result = es.submit(t);
futures.add(result);
}
Collection<Long> durations = futures.stream().map(f -> {
try {
return f.get();
}
catch (InterruptedException | ExecutionException exc) {
log.error("get", exc);
return -1l;
}
}).collect(Collectors.toList());
log.info("Test with execution service duration = {}", System
.currentTimeMillis() - testStart);
log.info("Maximum duration = {}", durations.stream().mapToLong(l -> l).max()
.getAsLong());
futures.clear();
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment