class aa extends Thread{
public static int n=0;
static synchronized void inc()
{
n++;
}
public void run(){
for(int i=0;i<10;i++){
try{
inc();
sleep(3);
}catch (Exception e){
}
}
}
}
public class bb {
public static void main(String[] args) throws Exception {
Thread threads[]=new Thread[100]; //声明100个线程
for(int i=0;i<threads.length;i++) //建立100个线程
threads[i]=new aa();
for(int i=0;i<threads.length;i++) //运行刚刚建立的100个线程
threads[i].start();
for(int i=0;i<threads.length;i++) //100个线程都执行完后再继续
threads[i].join();
System.out.println("n="+aa.n);
}
}
运行结果:
n=1000
心得:
join()方法的功能是使异步执行的线程变成同步执行,即保证要得到结果时,该线程已执行完毕。