??
??
Focus: Blocking and event-driven programming
??
??
There is time to implement the above small example
??
??
??
??
??
??
??
??
??
??
Package COM.BINGFA;
??
Import java.util.concurrent.*;
Import java.util.*;
??
Class Taskwithresult implements Callable<string> {
private int id;
public taskwithresult (int id) {
This.id = ID;
}
Public String call () {
Return "result of Taskwithresult" + ID;
}
}
??
public class Callabledemo {
public static void Main (string[] args) {
Executorservice exec = Executors.newcachedthreadpool ();
arraylist<future<string>> results =
New Arraylist<future<string>> ();
for (int i = 0; i <; i++)
Results.add (Exec.submit (New Taskwithresult (i)));
for (future<string> fs:results)
try {
Get () blocks until completion:
System.out.println (Fs.get ());
} catch (Interruptedexception e) {
System.out.println (e);
Return
} catch (Executionexception e) {
System.out.println (e);
} finally {
Exec.shutdown ();
}
}
}/* Output:
Result of Taskwithresult 0
Result of Taskwithresult 1
Result of Taskwithresult 2
Result of Taskwithresult 3
Result of Taskwithresult 4
Result of Taskwithresult 5
Result of Taskwithresult 6
Result of Taskwithresult 7
Result of Taskwithresult 8
Result of Taskwithresult 9
*///:~
??
??
??
??
21st Chapter Concurrency