Skip to content

Instantly share code, notes, and snippets.

@Kylar42
Created February 2, 2018 21:32
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 Kylar42/a825313e5a6bb1f1f2f962e4a7550522 to your computer and use it in GitHub Desktop.
Save Kylar42/a825313e5a6bb1f1f2f962e4a7550522 to your computer and use it in GitHub Desktop.
Thread Example with CompletableFuture
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
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.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadTest {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(5);
AtomicInteger foo = new AtomicInteger(0);
Collection<CompletableFuture<String>> units = new ArrayList<>();
for(int i = 0; i< 100; i++ ){
units.add(CompletableFuture.supplyAsync(
() -> {
int val = foo.getAndIncrement();
if (val % 4 == 0) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Success for instance - " + val;
}, service));
}
CompletableFuture allOf = CompletableFuture.allOf(units.toArray(new CompletableFuture[units.size()]));
//wait for 30 seconds
try {
allOf.get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
System.out.println("ALL DONE. LET's COUNT");
for(CompletableFuture<String> unit : units){
System.out.println("unit:"+unit);
System.out.println("Done:"+unit.isDone());
System.out.println("Is Cancelled:"+unit.isCancelled());
System.out.println("Is Completed Exceptionally:"+unit.isCompletedExceptionally());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment