题目
有20个线程,需要同时启动。
每个线程按0-19的序号打印,如第一个线程需要打印0
请设计代码,在main主线程中,等待所有子线程执行完后,再打印 ok
代码以及注释
public class Soultion {public static void main(String[] args) throws InterruptedException {int n=20;//创建一个线程数组用来存储20个线程Thread[]threads=new Thread[n];//实例化20个线程到线程数组中for(int i=0;i<n;i++){int finalI = i;threads[i]=new Thread(new Runnable() {@Overridepublic void run() {System.out.print(finalI+" ");}});}//启动所有的线程for(int i=0;i<n;i++){threads[i].start();}//等待所有的线程都执行完for(int i=0;i<n;i++){threads[i].join();}System.out.println("OK");}
}