Created
October 28, 2015 07:59
-
-
Save alexnitu88/a9028ed8215d5f98bcf4 to your computer and use it in GitHub Desktop.
WaitForMultipleThreadsToComplete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
/** | |
* Created by Alex on 10/28/2015. | |
*/ | |
public class WaitForMultipleThreadsToComplete { | |
public static void main(String[] args) { | |
// startJoinExample(); | |
startExecutorExample(); | |
} | |
private static void startExecutorExample() { | |
List<Callable<Object>> callables = new LinkedList<>(); | |
for (int i = 0; i< 10; i++) { | |
callables.add(new Callable<Object>() { | |
@Override | |
public Object call() throws Exception { | |
int time = new Random().nextInt(5000); | |
System.out.println("Thread will run for " + time + " ms"); | |
Thread.sleep(time); | |
return null; | |
} | |
}); | |
} | |
ExecutorService executor = Executors.newCachedThreadPool(); | |
long t0 = System.currentTimeMillis(); | |
try { | |
List<Future<Object>> results = executor.invokeAll(callables); | |
} catch (InterruptedException e) { | |
} | |
long t1 = System.currentTimeMillis(); | |
System.out.println("---------- Total work time " + (t1 - t0) + " ms"); | |
} | |
private static void startJoinExample() { | |
List<Thread> threads = new LinkedList<>(); | |
for (int i = 0; i < 10 ; i++) { | |
Thread t = new Thread() { | |
@Override | |
public void run() { | |
try { | |
int time = new Random().nextInt(5000); | |
System.out.println("Thread will run for " + time + " ms"); | |
Thread.sleep(time); | |
} catch (InterruptedException e) { | |
} | |
} | |
}; | |
threads.add(t); | |
t.start(); | |
} | |
long t0 = System.currentTimeMillis(); | |
for (Thread t : threads) { | |
try { | |
t.join(); | |
} catch (InterruptedException e) { | |
} | |
} | |
long t1 = System.currentTimeMillis(); | |
System.out.println("---------- Total work time " + (t1 - t0) + " ms"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment