Skip to content

Instantly share code, notes, and snippets.

@BioQwer
Created March 28, 2016 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BioQwer/1100b83b0d45b0e20c48 to your computer and use it in GitHub Desktop.
Save BioQwer/1100b83b0d45b0e20c48 to your computer and use it in GitHub Desktop.
Concurrency
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class DeleteMe {
private static class TestConcurrency implements Callable<Integer> {
private int time;
public TestConcurrency(int time) {
this.time = time;
}
@Override
public Integer call() throws Exception {
if (time == 666) {
throw new Exception("Burn!");
}
Thread.currentThread().sleep(100 * time);
System.out.println(Thread.currentThread().getName() + " " + time);
return time;
}
}
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Future<Integer>> tasksList = new ArrayList<>();
tasksList.add(executorService.submit(new TestConcurrency(20)));
tasksList.add(executorService.submit(new TestConcurrency(3)));
tasksList.add(executorService.submit(new TestConcurrency(1)));
tasksList.add(executorService.submit(new TestConcurrency(666)));
tasksList.add(executorService.submit(new TestConcurrency(2)));
ArrayList<Object> result = new ArrayList<>();
try {
executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);
/*while (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { //// FIXME: Смысл этого while из него не бросается Exception?
System.out.println("I'm in while!");
for (Future<Integer> task : tasksList) {
task.get();
}
System.out.println("And what??");
}*/
for (Future<Integer> task : tasksList) {
result.add(task.get());
}
} catch (InterruptedException ie) {
executorService.shutdownNow();
} catch (java.util.concurrent.ExecutionException cee) {
Throwable cause = cee.getCause();
if (cause instanceof InterruptedException) {
throw (InterruptedException) cee.getCause();
} else {
throw (Exception) cee.getCause();
}
}
System.out.println("result = " + result);
System.out.println("Finish");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment