从 5.2 开始,aviatorscript 支持 use 语句,类似 java 里的 import 语句,可以导入 java 类到当前命名空间,减少在 new 或者 try…catch 等语句里写完整报名的累赘方式。 use 语句的使用方式多种,最简单的情况是导入单个 Java 类:

    1. ## examples/new.av
    2. use java.util.Date;
    3. let d = new Date();
    4. p(type(d));
    5. p(d);

    use 包名.类名 就可以导入任意一个类到当前上下文。

    如果要导入某个包下面的任意类,可以用通配符 *

    1. ## examples/use.av
    2. use java.util.*;
    3. let list = new ArrayList(10);
    4. seq.add(list, 1);
    5. seq.add(list, 2);
    6. p("list[0]=#{list[0]}");
    7. p("list[1]=#{list[1]}");
    8. let set = new HashSet();
    9. seq.add(set, "a");
    10. seq.add(set, "a");
    11. p("set type is: " + type(set));
    12. p("set is: #{set}");

    我们把 java.util 包下的类都导入,因此可以直接 new 一个 ArrayList 或者 HashSet,并使用:

    1. list[0]=1
    2. list[1]=2
    3. set type is: java.util.HashSet
    4. set is: [a]

    如果你只是想引入包下的数个类,而不是全部,可以通过 use 包名.{类1, 类2...} 的方式,看一个更复杂的例子

    1. use java.util.concurrent.locks.{ReentrantLock, ReentrantReadWriteLock};
    2. use java.util.concurrent.CountDownLatch;
    3. let x = 0;
    4. let n = 10;
    5. let lk = new ReentrantLock();
    6. let latch = new CountDownLatch(n);
    7. for i in range(0, n) {
    8. let t = new Thread(lambda() ->
    9. lock(lk);
    10. x = x + 1;
    11. unlock(lk);
    12. countDown(latch);
    13. p("thread #{i} done");
    14. end);
    15. start(t);
    16. }
    17. await(latch);
    18. p("x=#{x}");
    19. let lk = new ReentrantReadWriteLock();
    20. let wlk = writeLock(lk);
    21. lock(wlk);
    22. x = x + 1;
    23. unlock(wlk);
    24. p("x=#{x}");

    我们使用 ReentranLock 来保护变量 x ,并且使用 CountDownLatch 来同步所有线程执行完成。接下来我们用 ReentrantReadWriteLock 读写锁来保护 x 。可以看到 use java.util.concurrent.locks.{ReentrantLock, ReentrantReadWriteLock}; 这一行代码导入了两个 Lock 类。

    执行输出:

    1. thread 4 done
    2. thread 5 done
    3. thread 2 done
    4. thread 0 done
    5. thread 3 done
    6. thread 1 done
    7. thread 6 done
    8. thread 7 done
    9. thread 8 done
    10. thread 9 done
    11. x=10
    12. x=11
    13. null