1、在上面的例子中多次使用到了Thread类的join方法。我想大家可能已经猜出来join方法的功能是什么了。对,join方法的功能就是使异步执行的线程变成同步执行。也就是说,当调用线程实例的start方法后,这个方法会立即返回,如果在调用start方法后后需要使用一个由这个线程计算得到的值,就必须使用join方法。如果不使用join方法,就不能保证当执行到start方法后面的某条语句时,这个线程一定会执行完。而使用join方法后,直到这个线程退出,程序才会往下执行。下面的代码演示了join的用法。packagemythread;public class JoinThread extends Th
2、read{ public static volatile int n = 0; public void run() { for (int i = 0; i < 10; i++, n++) try { sleep(3); // 为了使运行结果更随机,延迟3毫秒 } catch (Exception e) { } }
3、public static void main(String[] args) throws Exception { Thread threads[] = new Thread[100]; for (int i = 0; i < threads.length; i++) // 建立100个线程 threads[i] = new JoinThread(); for (int i = 0; i < threads.length; i++) // 运行刚才建立的100个线程 threads[i].star
4、t(); if (args.length > 0) for (int i = 0; i < threads.length; i++) // 100个线程都执行完后继续 threads[i].join(); System.out.println("n=" + JoinThread.n); }} 在例程2-8中建立了100个线程,每个线程使静态变量n增加10.如果在这100个线程都执行完后输出n,这个n值应该是1000. 1. 测试1 使用如下的命令运行上面程序:javamythread.Jo