21.10 活动对象 - 图1

    1. import java.util.concurrent.*;
    2. import java.util.*;
    3. public class ActiveObjectDemo1 {
    4. private ExecutorService ex = Executors.newFixedThreadPool(1);
    5. private Random rand = new Random(47);
    6. private void pause(int factor) {
    7. try {
    8. TimeUnit.MILLISECONDS.sleep(100 + rand.nextInt(factor));
    9. } catch (InterruptedException e) {
    10. System.out.println("sleep() interrupted");
    11. }
    12. }
    13. public Future<Integer> calculateInt(final int x, final int y) {
    14. return ex.submit(new Callable<Integer>() {
    15. public Integer call() {
    16. System.out.println(Thread.currentThread().getName() + "->" + "starting " + x + " + " + y);
    17. pause(500);//模拟计算的过程
    18. return x + y;
    19. }
    20. });
    21. }
    22. public Future<Float> calculateFloat(final float x, final float y) {
    23. return ex.submit(new Callable<Float>() {
    24. public Float call() {
    25. System.out.println(Thread.currentThread().getName() + "->" + "starting " + x + " + " + y);
    26. pause(2000);
    27. return x + y;
    28. }
    29. });
    30. }
    31. public void shutdown() {
    32. ex.shutdown();
    33. }
    34. public static void main(String[] args) {
    35. ActiveObjectDemo d1 = new ActiveObjectDemo();
    36. // Prevents ConcurrentModificationException:
    37. List<Future<?>> results = new CopyOnWriteArrayList<Future<?>>();
    38. for (float f = 0.0f; f < 1.0f; f += 0.2f)
    39. results.add(d1.calculateFloat(f, f));
    40. for (int i = 0; i < 5; i++)
    41. results.add(d1.calculateInt(i, i));
    42. System.out.println("All asynch calls made");
    43. //1,results可能添加一个null 但其size为1
    44. while (results.size() > 0) {
    45. for (Future<?> f : results)
    46. //2,不阻塞 没关系,但其是一直遍历的
    47. if (f.isDone()) {
    48. try {
    49. System.out.println("res="+f.get());//4,获取结果的时候去阻塞的,获取完结果再去remove
    50. } catch (Exception e) {
    51. throw new RuntimeException(e);
    52. }
    53. results.remove(f);//3,当把所有结果都移除后 while的size才为0
    54. }
    55. }
    56. d1.shutdown();
    57. }
    58. }