1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
import java.util.concurrent.*; import java.util.logging.Level; import java.util.logging.Logger;
class MyRunnable implements Runnable {
private final long waitTime;
public MyRunnable(int timeInMillis) { this.waitTime = timeInMillis; }
@Override public void run() { try { Thread.sleep(waitTime);
System.out.println(Thread .currentThread() .getName()); }
catch (InterruptedException ex) { Logger .getLogger(MyRunnable.class.getName()) .log(Level.SEVERE, null, ex); } } }
class FutureTaskExample {
public static void main(String[] args) { MyRunnable myrunnableobject1 = new MyRunnable(1000); MyRunnable myrunnableobject2 = new MyRunnable(2000);
FutureTask<String> futureTask1 = new FutureTask<>(myrunnableobject1, "FutureTask1 is complete"); FutureTask<String> futureTask2 = new FutureTask<>(myrunnableobject2, "FutureTask2 is complete");
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(futureTask1);
executor.submit(futureTask2);
while (true) { try {
if (futureTask1.isDone() && futureTask2.isDone()) {
System.out.println("Both FutureTask Complete");
executor.shutdown(); return; }
if (!futureTask1.isDone()) {
System.out.println("FutureTask1 output = " + futureTask1.get()); }
System.out.println("Waiting for FutureTask2 to complete");
String s = futureTask2.get(250, TimeUnit.MILLISECONDS);
if (s != null) { System.out.println("FutureTask2 output=" + s); } }
catch (Exception e) { Sysmtem.out.println("Exception: " + e); } } } }
|